0

I have the following tables:

Customer(login varchar, town varchar)
Orders (Ordno int , login varchar) >>login Fk from Customer
combination (Id int, ordno int ,Product_Id int) >>ordno fk from orders

I need to show the products that have been sold in ALL the cities.

Example:

Insert into Customer (log1 , NY) (log2, NY) (log3, London)
Insert into Orders (1,log1) (2,log1) (3,log3) 
Insert into combination (1,1,1) (2,2,2) (3,3,1) 
  • Product 1 sold in NY
  • product 2 sold in NY
  • product 1 sold in London

if the available cities are only NY and London, then the only product that must be the result of the query is product 1

4

3 回答 3

2
SELECT  a.ProductID
FROM    Combination a
        INNER JOIN Orders b
            ON a.OrdNo = b.OrdNo
        INNER JOIN Customer c
            ON b.Login = c.LogIn
GROUP   BY a.ProductID
HAVING  COUNT(DISTINCT a.ID) = (SELECT COUNT(DISTINCT town) FROM Customer)
于 2013-04-25T11:17:36.803 回答
0

不知道你到底想在这里做什么。

SELECT c.Town, cc.Product_Id FROM from Customer c
JOIN Orders o ON c.login = o.login
JOIN Combination cc ON o.Ordno = cc.ordNo
GROUP BY c.town

这会将城镇组合在一起并向您显示 Product_Id

您仍然需要一个产品表来显示产品表。

此查询不包括产品表

于 2013-04-25T11:16:55.717 回答
0

假设 Products 表如下所示:

Products (Product_Id int, Name)

您需要将东西一路向下(或向上)连接到客户......

SELECT p.Name, c.town
FROM Products p
  INNER JOIN Combination comb ON comb.Product_Id=p.Product_Id
  INNER JOIN Orders o ON o.Ordno=comb.ordno
  INNER JOIN Customer cust ON cust.login=o.login
GROUP BY p.Name, c.town
于 2013-04-25T11:17:37.430 回答