1

作为我正在寻找的示例,请考虑以下示例水果表


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”和“dried”的用户的所有记录(不一定同时在同一行)。同一个用户必须同时具备这两个条件。

我想要返回的是:


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

4

4 回答 4

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
于 2012-10-15T11:54:34.397 回答
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)
于 2012-10-15T12:27:56.463 回答
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
于 2015-05-19T07:18:12.923 回答
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')
于 2015-05-19T08:20:37.820 回答