从2个表进行SQL查询以匹配条件

时间:2018-12-03 14:16:28

标签: sql oracle

我在寻找正确的SQL查询时遇到了问题。我有一个api休息电话

/order?[customerID=][year=][address=][item=][country=]

,我必须执行一个SQL查询以根据URL中的值返回order(orderID,order desc)。在数据库中,我有2个表

表1

customerName
customerID
year
orderID
orderDesc
country

表2

customerName
customerID
year
address
item
quantity
orderID

我需要从Table1中获得orderID和orderDesc,这要满足customerID,year,country等于Table1中URL的值以及Table2中的customerID,year,address,item的条件(请记住,orderID应该是相同)。这可能吗。我是SQL的新手,正在努力寻找解决方案。任何帮助将不胜感激

Adrin

3 个答案:

答案 0 :(得分:1)

这很简单:

select t1.orderID, t1.orderDesc
from Table1 t1
inner join Table2 t2 on t1.orderID=t2.orderID and t1.customerID=t2.customerID and t1.year=t2.year
Where t2.address=@address and t1.year=@year and t1.customerID=@customerID and t2.item=@item and t1.country=@country

您必须声明var或创建一个存储过程。

为此,两个表中的customerID必须相同,条件是内部联接后的“ ON”。

答案 1 :(得分:1)

按照Tim的建议,我建议在继续之前进行规范化,但是如果必须继续,一种可能的解决方案是使用联接。

    SELECT t1.OrderID, t1.ORderDesc
    FROM Table1 AS t1
INNER JOIN Table2 AS t2 
ON t1.OrderID = t2.OrderID
WHERE t1.CustomerID = @CustomerID
AND t2.CustomerID = @CustomerID
AND t1.Year = @Year
AND t2.Year = @Year
AND t1.Country = @Country
AND t2.Address = @Address
AND t2.Item = @Item

@ Item,@ Year,@ Country和@CustomerID是从URL解析的值的参数。

我希望这会有所帮助:)

答案 2 :(得分:1)

您可以联接两个表,并使用WHERE子句根据API接收的参数过滤结果。

但是请不要因为这太丑陋了……在两个表之间似乎有很多冗余信息,正如@TimBiegeleisen所评论的那样,您最好在之前标准化您的数据结构;这样会使查询的逻辑更加简洁。

select
    a.customerID,
    a.orderDesc
from table1 a
join table2 b 
    on b.orderID = a.orderID
    and b.customerName = a.customerName
    and b.year = a.year
    and b.customerID = a.customerID
where
    a.customerID = :CUSTOMERID 
    and a.year = :YEAR
    and b.address = :ADDRESS
    and b.item = :ITEM
    and a.country = :COUNTRY
相关问题