MySQL选择组合唯一

时间:2015-01-27 03:45:17

标签: mysql select join

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
name  | thing
-------------
Terry | stuff
Tom   | stuff
Henry | 
Toby  | stuff

基本上,我想我想要一个JOIN,但我希望表2中的任何名称(has_thing)不在表1中,包括输出和表1中的任何名称(联系人)WHERE has_this = 1要包含在输出中

1 个答案:

答案 0 :(得分: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)可确保我们在联系人thing时从第一个查询中选择非空has_thing = 1

您也可以使用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