如何在mysql上添加条件以根据列值获取不同表的值

时间:2018-04-16 10:10:28

标签: mysql

美好的一天,

我想加入4个表。现在我想根据事务类型获取每个事务的详细信息,例如。如果

交易表

id |     type    |  source_id
 1   'product'         1
 2   'reservation'     1
 3   'service'         1 

产品表

 id | Name     
  1 | product 1     

预订表

 id | reservation name        | other details
  1 |  some reservation name  | ------

服务表

 id | Service Name            | Other details
  1 | House Cleaning Service  | ------------

这是我想要的表格

id |     type    |  source_id  | product_name  | reservation_name | service name
 1   'product'         1         product 1           null              null
 2   'reservation'     1             null      some reservation name   null
 3   'service'         1            null             null              House Cleaning Service

目前我最疯狂的猜测是

select a.id,a.type,a.source_id,b.product_name,c.reservation_name,d.service_name
from transaction as a
left join product_table as b on a.source_id = b.id
left join reservation_table as c on a.source_id = c.id
left join services_table as d on a.source_id = d.id

我确定它不会100%工作:D

有没有办法添加条件,如果'type'column ='product'那么它只从product表中提取?

3 个答案:

答案 0 :(得分:1)

你可以尝试这样的CASE指令:

select a.id,a.type,a.source_id,
       CASE a.source_id
           WHEN 'product'  THEN b.product_name
           else  null
       END ,
       CASE a.source_id
           WHEN 'reservation'  THEN c.reservation_name
           else  null
       END ,
       CASE a.source_id
           WHEN 'service'  THEN d.service_name
           else  null
       END 
from transaction as a
left join product_table as b on a.source_id = b.id
left join reservation_table as c on a.source_id = c.id
left join services_table as d on a.source_id = d.id

答案 1 :(得分:1)

在加入中添加条件 像

select a.id,a.type,a.source_id,b.product_name,c.reservation_name,d.service_name
from transaction as a
left join product_table as b on a.source_id = b.id and a.type='product'
left join reservation_table as c on a.source_id = c.id and a.type='reservation'
left join services_table as d on a.source_id = d.id and a.type='service'

答案 2 :(得分:-1)

select  a.id,a.type,a.source_id,b.product_name,c.reservation_name,d.service_name
from transaction as a
left join product_table as b on a.source_id = b.id
left join reservation_table as c on a.source_id = c.id
left join services_table as d on a.source_id = d.id WHERE a.type = 'product' 

试试这个希望它会帮助你