[英]how can I add condition on mysql to get value on different table base on column value
美好的一天,
我有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'列='product',那么它只能從products表中提取?
您可以嘗試使用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
在連接中添加條件,例如
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'
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'
嘗試這一希望對您有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.