(高级)数据库关联表上的SQL查询

时间:2014-08-10 10:19:24

标签: sql database select

假设在数据库中的关联中有一个表:

Customer(Id, Name, City),

Orders(Cust_Id, Prod_Id),

Product(Id, Name, Price, Country)

理所当然Customer只订购了一次特定Product,我想执行以下查询:

1)获取来自Customers" XY" Products的{​​{1}}有序全部

这是解决方案吗?:

Country

2)从Select * from Customers c join Orders o on c.id = o.orders.cust_id join Product p on o.prod_id = p.id where p.id = (Select id from Product where Product.country = "XY") " XY"

获取Customers订购的Products

两种情况下的正确查询是什么?

1 个答案:

答案 0 :(得分:0)

1)订购特定国家/地区的所有产品的客户:

DECLARE @Country AS VARCHAR(100)
SET @Country = 'XY'
;WITH OrdersCTE AS
(
    SELECT *
    FROM   Orders
    WHERE  Prod_Id IN (SELECT Id FROM Product WHERE Country = @Country)
)
SELECT * 
FROM   Customers
WHERE  Id IN 
(
    SELECT Cust_Id 
    FROM   OrdersCTE
    GROUP BY Cust_Id 
    HAVING COUNT(DISTINCT Prod_Id) = (SELECT COUNT(*) FROM Product WHERE Country = @Country)
)

2)仅购买特定国家/地区的产品的客户:

DECLARE @Country AS VARCHAR(100)
SET @Country = 'XY'
SELECT   C.Id,
         C.Name,
         C.City
FROM     Customers C
         Left JOIN Orders O
             ON C.Id = O.Cust_Id
         LEFT JOIN Product P
             ON P.Id = O.Prod_Id
GROUP BY C.Id,
         C.Name,
         C.City
HAVING   COUNT(DISTINCT Country) = 1