SQL 一对多条件问题
SQL One to Many Condition Issue
我有两张桌子
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
如果用户居住在国家/地区 = 1,我想要购买的产品列表
Select Orders.Product from users left join Users.ID = ORDERS.ID WHERE COUNTRY = 1
工作正常
如果用户居住在国家/地区 = 1 并带来了 macbook Pro(但不在列表中显示 macbook pro),如果我想要购买的产品列表怎么办
所以只显示
AppleTV
iPAD pRO
经典写作SQL你有一个分层子select。
应该工作的代码:
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'))
对此的快速回答很简单。首先,select 购买了 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')
效果很好。
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
我有两张桌子
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
如果用户居住在国家/地区 = 1,我想要购买的产品列表
Select Orders.Product from users left join Users.ID = ORDERS.ID WHERE COUNTRY = 1
工作正常
如果用户居住在国家/地区 = 1 并带来了 macbook Pro(但不在列表中显示 macbook pro),如果我想要购买的产品列表怎么办
所以只显示
AppleTV
iPAD pRO
经典写作SQL你有一个分层子select。 应该工作的代码:
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'))
对此的快速回答很简单。首先,select 购买了 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')
效果很好。
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