如何在mysql上添加条件,以便根据列值在不同的表上获取值
你好 我有4个表,我正试图加入。现在,我想根据交易类型获得每个交易的详细信息,例如,如果 事务表如何在mysql上添加条件,以便根据列值在不同的表上获取值,mysql,Mysql,你好 我有4个表,我正试图加入。现在,我想根据交易类型获得每个交易的详细信息,例如,如果 事务表 id | type | source_id 1 'product' 1 2 'reservation' 1 3 'service' 1 id | reservation name | other details 1 | some reservation name | ------ 产品表 id
id | type | source_id
1 'product' 1
2 'reservation' 1
3 'service' 1
id | reservation name | other details
1 | some reservation name | ------
产品表
id | Name
1 | product 1
预订表
id | type | source_id
1 'product' 1
2 'reservation' 1
3 'service' 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%起作用
是否有一种方法可以添加一个条件,即如果“type”列=“product”,那么它只能从products表中提取
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'
试试这一个,希望它能帮助你你可以试试下面的案例说明:
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
在联接中添加条件
像
嗯,抱歉@sushil,但我肯定这行不通。。将其中的a.type='product'表示筛选结果仅包含产品类型。。我的问题是要让这三种类型显示在同一个表中,但基于a.typewow在不同的列上。你真的能在join上添加条件吗?谢谢你的回答!是的,如果您要使用,请标记正确答案