我有两张桌子
Table1 (Users)
ID, NAME, COUNTRY
1, Joe Bloggs, 1
2, Joe Jnr, 1
3, Joe Snr, 2
Table2 (Orders)
UsersID, Product
1, Apple TV
1, iPad Pro
1, MacBook Pro
2, iPad Mini
2, iPad Pro
3, iPad Air
3, iPad Pro
如果我想要一个产品列表,如果用户居住在Country = 1
Select Orders.Product from users left join Users.ID = ORDERS.ID WHERE COUNTRY = 1
工作正常
如果我想要一个产品列表,如果用户居住在country = 1并带来macbook Pro(但没有在列表中显示macbook pro),该怎么办?
所以只需显示
AppleTV
iPAD pRO
答案 0 :(得分:1)
在经典SQL中编写一个分层子选择。 应该有效的代码:
Select Product from Orders
Where Product <> 'MacBook Pro' -- you don't want MacBook Pro in results
and UsersID in
(Select ID from Users
where country = '1' --get all Country 1 users that Purchased MacBooks
and ID in
(Select B.UsersID
from Orders B --- aliased for clarity
where Product = 'MacBook Pro'))
答案 1 :(得分:1)
快速回答这个问题很简单。首先,选择购买MacBook Pro的用户以及居住在该国家/地区的用户:
SELECT T_USERS.id
FROM Users T_USERS INNER JOIN Orders T_ORDERS
ON (T_USERS.id = T_ORDERS.UsersID)
WHERE T_USERS.Country = 1
AND T_ORDERS.product = 'MacBook Pro'
然后,在子查询中使用它来获取用户并避免包含MacBook产品的行:
SELECT Product
FROM Orders
WHERE product <> 'MacBook Pro'
AND UsersID IN (SELECT T_USERS.id
FROM Users T_USERS INNER JOIN Orders T_ORDERS
ON ( T_USERS.id = T_ORDERS.UsersID )
WHERE T_USERS.country = 1
AND T_ORDERS.product = 'MacBook Pro')
它运作得很好。
答案 2 :(得分:0)
Select distinct o1.Product
from Orders o1
inner join Orders o2
on o1.UserId = o2.UserId
and o2.Product = 'MacBook Pro'
inner join Users u
on o1.UserId = u.Id
where o1.Product <> 'MacBook Pro'
and u.country = 1
order by o1.Product