我可以使用t1行作为t2行的键来从两个表中选择行吗?

时间:2018-03-31 01:01:03

标签: mysql

我有两张桌子:

id1,id2,... idX包含来自t2或null的id。我可以进行这样的选择,这会将t2中的参数放入t1吗?

例如我有一个t1(name,year,id1,id2,id3,id4)值:

name    year    id1    id2    id3    id4
------------------------------------------
marko    1999    1       2    null    1
polo     1985    null    null     5    3

和t2值:

id    info    param
--------------------------------------
1    apple    green
2    car    yellow
3    bee    pink
4    doctor     whiskey
5    book    small

所以我想基于t1行获得这样的动态查询结果:

SELECT name, year, id1-info, id1-param, id2-info, id2-param, id4-info, id4-param 
 FROM t1 WHERE name = 'marko'

SELECT name, year, id3-info, id3-param, id4-info, id4-param 
 FROM t1 WHERE name = 'marko'

我google了很多,但除了嵌套查询之外什么都没找到,例如:

SELECT 
  name, 
  year, 
  (SELECT `info` FROM t2 WHERE id = t1.id1) AS id1-info, 
  (SELECT `param` FROM t2 WHERE id = t1.id1) AS id1-param,
  (SELECT `info` FROM t2 WHERE id = t1.id2) AS id2-info...

但我明白,这是一个非常糟糕的主意,因为我在t1中有很多id列,它们不是静态的。或者如果它不能动态完成,我可以制作SELECT,它会在一行中显示所有内容:

SELECT name, year, id1-info, id1-param, id2-info, id2-param, id3-info, id3-param, id4-info, id4-param 
 FROM t1 WHERE name = 'marko'

1 个答案:

答案 0 :(得分:0)

要在一行中使用一个选择,您可以在t2上使用多个左连接。

SELECT name, 
       `year`, 
       id11.info as `id1-info`, 
       id11.param as `id1-param`, 
       id21.info as `id2-info`, 
       id21.param as `id2-param`, 
       id31.info as `id3-info`, 
       id31.param as `id3-param`, 
       id41.info as `id4-info`, 
      id41.param as `id4-param`
 FROM t1 
 LEFT JOIN t2 as id11 on t1.id1=id11.id
 LEFT JOIN t2 as id21 on t1.id2=id21.id
 LEFT JOIN t2 as id31 on t1.id3=id31.id
 LEFT JOIN t2 as id41 on t1.id4=id41.id
 WHERE name = 'marko';

  result:
  name  year    id1-info    id1-param   id2-info    id2-param   id3-info    id3-param   id4-info    id4-param
marko   1999    apple   green   car yellow  (null)  (null)  apple   green