Mysql 查找多个联接表之一的匹配类型

Mysql 查找多个联接表之一的匹配类型,mysql,sql,Mysql,Sql,我有几张桌子 表0 id | id_table_1 |id_table_2 | people_id 1 1 0 1 2 0 2 1 3 0 0 1 4 0 1 2 表1 id | machine| type 1 bmw 1 2 reno 1 ....

我有几张桌子

表0

id | id_table_1 |id_table_2 | people_id
1        1           0        1
2        0           2        1
3        0           0        1
4        0           1        2
表1

 id | machine| type
   1    bmw      1
   2    reno     1
     ....
表2

  id | machine |type
   1   yamaha     2
   2   ducati     3 
   ....
表3(类型)

我想做一个select查询,它可以得到这个结果

tabel_0.id | table_0.people_id  | machine(table_1 or table_2) |  type
    1                1                      bmw                  auto
    2                1                      ducati               sportbike
    3                1                       ""                    ""
上次我问了这个问题,但是没有行类型,现在我有了这个代码

    SELECT table_0.id, table_0.people_id, 
       IFNULL(table_1.machine, table_2.machine) AS machine
FROM table_0 
LEFT JOIN table_1 ON table_0.id_table_1 = table_1.id 
LEFT JOIN table_2 ON table_0.id_table_2 = table_2.id
WHERE table_0.people_id = 1
请帮助解决我的问题。谢谢

试试这个:

SELECT table_0.id, table_0.people_id, table_1.machine, table_2.machine , table_3.type
FROM table_0 
   JOIN table_1 ON table_0.id_table_1 = table_1.id 
   JOIN table_2 ON table_0.id_table_2 = table_2.id
   JOIN table_3 ON table_2.type = table_3.id
WHERE table_0.people_id = 1

您可以使连接到类型对
表1
表2
起作用:

select  t0.id
,       t0.people_id
,       coalesce(t1.machine, t2.machine) as machine
,       t3.name as type
from    table_0 t0
left join
        table_1 t1
on      t0.id_table_1 = t1.id
left join
        table_2 t2
on      t0.id_table_2 = t2.id
left join
        table_3 t3
on      t3.id in (t1.type, t2.type)

您可以通过为表提供实名而不是
table_1
table_2

来改进您的设计,您只需在表2中查找行的类型。对于表1和表2使用内部联接肯定无法返回任何行
select  t0.id
,       t0.people_id
,       coalesce(t1.machine, t2.machine) as machine
,       t3.name as type
from    table_0 t0
left join
        table_1 t1
on      t0.id_table_1 = t1.id
left join
        table_2 t2
on      t0.id_table_2 = t2.id
left join
        table_3 t3
on      t3.id in (t1.type, t2.type)