MySQL Select 组合唯一
MySQL Select Combined Unique
Table: Contacts
id | name | has_this
------------------------
1 | Jeff | 0
2 | Terry | 1
3 | Tom | 0
4 | Henry | 1
Table: has_thing
id | owner | thing
---------------------
1 | Terry | stuff
2 | Tom | stuff
3 | Toby | stuff
我想要一个 SELECT return
name | thing
-------------
Terry | stuff
Tom | stuff
Henry |
Toby | stuff
基本上,我想我想要一个 JOIN,但我希望 table 2(has_thing) 中不在 table 1 中的任何名称都包含在输出中,并且table 1(Contacts) WHERE has_this=1 中的任何名称都将包含在输出
中
SELECT name, MAX(thing) as thing
FROM (SELECT c.name, h.thing
FROM Contacts AS c
JOIN has_thing AS h ON c.name = h.name
UNION
SELECT name, ''
FROM Contacts
WHERE has_thing = 1) AS subquery
GROUP BY name
MAX(thing)
确保我们在联系人具有 has_thing = 1
.
时从第一个查询中获取非空 thing
你也可以用 LEFT JOIN
:
SELECT c.name, IFNULL(h.thing, '') AS thing
FROM Contacts AS c
LEFT JOIN has_thing AS h ON c.name = h.name
WHERE c.has_thing = 1
OR h.name IS NOT NULL
Table: Contacts
id | name | has_this
------------------------
1 | Jeff | 0
2 | Terry | 1
3 | Tom | 0
4 | Henry | 1
Table: has_thing
id | owner | thing
---------------------
1 | Terry | stuff
2 | Tom | stuff
3 | Toby | stuff
我想要一个 SELECT return
name | thing
-------------
Terry | stuff
Tom | stuff
Henry |
Toby | stuff
基本上,我想我想要一个 JOIN,但我希望 table 2(has_thing) 中不在 table 1 中的任何名称都包含在输出中,并且table 1(Contacts) WHERE has_this=1 中的任何名称都将包含在输出
中SELECT name, MAX(thing) as thing
FROM (SELECT c.name, h.thing
FROM Contacts AS c
JOIN has_thing AS h ON c.name = h.name
UNION
SELECT name, ''
FROM Contacts
WHERE has_thing = 1) AS subquery
GROUP BY name
MAX(thing)
确保我们在联系人具有 has_thing = 1
.
thing
你也可以用 LEFT JOIN
:
SELECT c.name, IFNULL(h.thing, '') AS thing
FROM Contacts AS c
LEFT JOIN has_thing AS h ON c.name = h.name
WHERE c.has_thing = 1
OR h.name IS NOT NULL