![](/img/trans.png)
[英]MySQL: LEFT JOIN or UNION table and set column value as column name?
[英]mysql: do left join on certain table if column has value
我有几张桌子: devices
、 acccessories
和repairs
。
Repairs
中有一个字段名为: item_type
和一个名为ref_id
item_type
的值可以是“1”,表示它是一个设备,或者“2”表示它是一个附件。
如果repairs.item_type = 1
我想在repairs.ref_id = devices.id
的那个表上进行连接。 如果repairs.item_type = 2
我想在repairs.ref_id = acccessories.id
的那个表上做一个连接。
我不知道该怎么做。
SELECT *
FROM repairs
LEFT JOIN repairs.ref_id = (if repairs.item_type = 1 then devices.id; if repairs.item_type = 2 then accessories.id)
有没有办法做到这一点,或者我需要做一个UNION ALL
像:
SELECT *
FROM repairs
LEFT JOIN repairs.ref_id = devices.id
WHERE repairs.item_id = '1'
UNION ALL
SELECT *
FROM repairs
LEFT JOIN repairs.ref_id = accessories.id
WHERE repairs.item_id = '2'
将devices
和accessories
表加入repair
表。
select t1.*
from repairs t1
left join devices t2 on t2.id = t1.ref_id
left join accessories t3 on t3.id = t1.ref_id
and t1.item_type in (1, 2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.