我有两个mysql表如下:
联系人
---------------
id | name | email
---------------
1 | Jack | jack@test.com
2 | John | john@test.com
3 | Liz | liz@test.com
5 | Jack | jack@test.com
6 | Liz | liz@test.com
7 | Mike | mike@test.com
8 | Jack | jack@test.com
购买
-------------------
id | contact_id | paid
-------------------
1 | 3 | true
2 | 5 | true
我需要使用独特的contact_ids来购买和购买其他独特的contact_ids。
所以最终的结果将是:
-------------------
id | name | email
------------------
2 | John | john@test.com
3 | Liz | liz@test.com
5 | Jack | jack@test.com
7 | Mike | mike@test.com
我尝试了查询:
SELECT * FROM contacts LEFT JOIN purchases ON contacts.id = purchases.user_id
但这并没有按要求给我独特的行。我尝试了几种DISTINCT组合,但我没有按要求得到结果。
答案 0 :(得分:1)
SELECT COALESCE(purchases.contact_id, contacts.id) as id, name, email
FROM contacts
LEFT JOIN purchases ON contacts.id = purchases.user_id
GROUP BY name
答案 1 :(得分:0)
这样的东西应该有效,但它的表现是“?”。
SELECT * FROM contacts WHERE id IN (
SELECT DISTINCT id as i FROM purchases
UNION
SELECT DISTINCT contact_id as i FROM purchases
)
GROUP BY id