mysql在条件下加入

时间:2015-01-09 21:12:13

标签: mysql join conditional-statements

我有这个表id_name:

+----+------+
| id | name |
+----+------+
| 1  |  one |
| 2  |  two |
| 3  | three|

...等,以及另一个表ids

+----+-----+-----+-----+----
| id | aid | bid | cid | ...
+----+-----+-----+-----+----
| 1  |  1  |  2  |  3  | ...
| 2  |  2  | null| null| ...
| 3  |  2  |  3  | null| ...

我想选择这样的东西:

+----+-----+-----+-----+-----+-----+-----+----
| id | aid |aname| bid |bname| cid |cname| ...
+----+-----+-----+-----+-----+-----+-----+----
| 1  |  1  | one |  2  | two |  3  |three| ...
| 2  |  2  | two | null| null| null| null| ...
| 3  |  2  | two |  3  |three| null| null| ...

基本上,如果id不为null,则将名称提取到相应的列,否则保持名称为null。

在我的项目中,我有7列(a-g)。

我尝试了7级联接,基本上类似于:

SELECT id,a.id AS aid,a.name AS aname,b.id AS bid,b.name AS bname, ...
  FROM ids AS t
JOIN id_name AS a ON a.id=t.aid
JOIN id_name AS b ON b.id=t.bid
... 

等。但后来我注意到,如果t.b为null,那么b.id = null总是为false,所以我不会选择任何行。 我怎样才能做一些像IF b.id IS NULL那么JOIN id_name AS b ON b.id = t.bid ELSE"保持bname null"?

据我所知,我可以创建一个临时表并进行7次更新。但有没有办法使用单个SELECT来完成这个?

谢谢!

3 个答案:

答案 0 :(得分:2)

您必须使用外部联接。例如

SELECT id,a.id AS aid,a.name AS aname,b.id AS bid,b.name AS bname, ...
  FROM ids AS t 
LEFT OUTER JOIN id_name AS a ON a.id=t.aid
LEFT OUTER JOIN id_name AS b ON b.id=t.bid
...

更多信息http://dev.mysql.com/doc/refman/5.0/en/join.html

答案 1 :(得分:0)

您也可以使用cross join获得结果,而无需多次加入同一个表

<强> SQL Fiddle

select ids.id, 
       aid, 
       max(case when aid = id_name.id then id_name.name end)  as aname, 
       bid, 
       max(case when bid = id_name.id then id_name.name end ) as bname
from ids
cross join id_name 
group by ids.id, aid, bid

答案 2 :(得分:0)

select
  i.id,
  a.id as aid,
  a.name as aname,
  b.id as bid,
  b.name as bname,
  c.id as cid,
  c.name as cname
from ids i
  left join id_name a
    on a.id = i.aid
  left join id_name b
    on b.id = i.bid
  left join id_name c
    on c.id = i.cid

SQL小提琴:http://www.sqlfiddle.com/#!2/3ea82/1