作为我正在寻找的示例,请考虑以下示例Fruits表
id user_id fruit type
1 43 apple fresh
2 87 watermelon fresh
3 99 apple fresh
4 43 pineapple dried
5 60 pineapple dried
6 60 lemon fresh
7 99 kiwi fresh
8 43 mango fresh
我想在同一个表中找到同时拥有“apple”和“dry”的所有用户的所有记录(不一定同时在同一行)。同一个用户必须同时拥有这两个条件。
我想要归还的是:
id user_id fruit type
1 43 apple fresh
4 43 pineapple dried
我尝试了几种自连接组合:
SELECT distinct f1.*, f2.*
FROM orders f1 FULL JOIN orders f2
ON f1.user_id = f2.user_id
WHERE f1.fruit ILIKE 'apple'
AND f2.type ILIKE 'dried'
但未能完全正确。
这适用于Rails应用程序,因此我很乐意能够使用ActiveRecord执行此操作,但如果需要,我会对纯SQL感到满意。
有关如何执行此操作的任何建议吗? TIA
答案 0 :(得分:2)
SELECT
orders.*
FROM
orders
INNER JOIN
(SELECT user_id FROM orders WHERE fruit = 'apple' GROUP BY user_id) AS apple_buyers
ON apple_buyers.user_id = orders.user_id
INNER JOIN
(SELECT user_id FROM orders WHERE type = 'dried' GROUP BY user_id) AS dried_buyers
ON dried_buyers.user_id = orders.user_id
答案 1 :(得分:2)
这应该适合你:
SELECT
*
FROM
Fruits
WHERE
(Fruit = 'apple'
OR Type = 'dried')
AND
EXISTS
(SELECT
NULL
FROM
FRUITS F1
INNER JOIN Fruits F2 ON F1.User_ID = F2.User_ID AND F1.Fruit = 'apple' and F2.Type = 'dried'
WHERE
Fruits.user_ID = F1.User_ID)
答案 2 :(得分:1)
select TAB1.id,TAB1.user_id,TAB1.fruit,TAB1.types
FROM
(select id,user_id,fruit,types
from IID T1 WHERE T1.fruit='apple' OR T1.types ='dried')TAB1
INNER JOIN
(select user_id,count(user_id) AS CNT_user_id
from IID T1 WHERE T1.fruit='apple' OR T1.types ='dried'
group by user_id
having count(user_id) >=2)TAB2
ON(TAB1.user_id=TAB2.user_id)
id user_id fruit types
4 43 pineapple dried
1 43 apple fresh
答案 3 :(得分:0)
SELECT A.id , A.user_id,A.fruit,A.types FROM iid A
WHERE user_id IN(
SELECT A.user_id FROM
(
SELECT user_id FROM iid
WHERE types='dried'
)A
INNER JOIN
(
SELECT user_id FROM iid WHERE fruit = 'apple'
)B
ON A.user_id=b.user_id)
AND ( fruit='apple' OR types='dried')