MySQL使用UNION

时间:2016-04-17 03:19:31

标签: mysql sql database join union

这个问题有点长,所以很明显,提前谢谢!

简介

我目前有3个表使用多对多关系。我需要查询所有3个表并将它们组合成1个表。

问题

我试过这个问题:

SELECT * FROM  `login` LEFT JOIN membership ON login.id = membership.login_id UNION SELECT * FROM  `login` RIGHT JOIN membership ON login.id = membership.login_id

它返回:

+----+------+----------+
| id | name | group_id |
+----+------+----------+
|  1 | Tom  |        6 |
|  2 | John |        8 |
|  3 | Jane |        4 |
+----+------+----------+

问题

我需要它还包括group_name。这是我想要的输出:

+----+------+----------+------------+
| id | name | group_id | group_name |
+----+------+----------+------------+
|  1 | Tom  |        6 | Red        |
|  2 | John |        8 | Brown      |
|  3 | Jane |        4 | Purple     |
+----+------+----------+------------+

login

  

具有自动递增ID

的所有用户的列表
+----+------+
| id | name |
+----+------+
|  1 | Tom  |
|  2 | John |
|  3 | Jane |
+----+------+

group

  

包含group_idgroup_name

的所有群组的列表
+----------+------------+
| group_id | group_name |
+----------+------------+
|        1 | Green      |
|        2 | Blue       |
|        3 | Yellow     |
|        4 | Purple     |
|        5 | Orange     |
|        6 | Red        |
|        7 | Pink       |
|        8 | Brown      |
+----------+------------+

membership

  

存储有关哪个用户属于哪个组的信息

+----------+----------+
| login_id | group_id |
+----------+----------+
|        1 |        6 |
|        2 |        8 |
|        3 |        4 |
+----------+----------+

2 个答案:

答案 0 :(得分:2)

同时加入group表并从表中选择所需的字段。

SELECT l.id,l.name,m.group_id,g.group_name
FROM  `login` l
LEFT JOIN `membership` m ON l.id = m.login_id 
LEFT JOIN `group` g on g.group_id = m.group_id

答案 1 :(得分:2)

试试这个......:)

SELECT 
  `login`.`id`,
  `login`.`name`,
  `group`.`group_id`,
  `group`.`group_name`
FROM
  `membership`
  INNER JOIN `login` ON (`membership`.`login_id` = `login`.`id`)
  INNER JOIN `group` ON (`membership`.`group_id` = `group`.`group_id`)