我在mysql中有三个表:
1.t_item
itemID item_name
1 pen
2 luxury pen
2.s_item
itemID item_name
1 shoes
2 clothes
3 computer
3.track
trackID item_no item_type
1 1 t_item
2 2 t_item
3 2 s_item
我想获得trackID,表轨道中item_no的项目名称。 如何编写sql语句?在track中,trackID 2,3具有相同的item_no但不同的项类型,我可以使用join吗?
答案 0 :(得分:0)
你走了,它会起作用:
(SELECT t.trackID,ti.item_name
FROM track t
LEFT JOIN t_item ti
ON t.item_no=ti.itemID AND t.item_type='t_item')
UNION
(SELECT t.trackID,si.item_name
FROM track t
LEFT JOIN s_item si
ON t.item_no=si.itemID AND t.item_type='s_item')
答案 1 :(得分:0)
是的,您可以像这样使用JOIN
:
SELECT t.trackID, t.item_no,
(CASE WHEN t.item_type = 't_item' THEN ti.item_name
WHEN t.item_type = 's_item' THEN si.item_name
END) AS item_name
FROM track t
LEFT JOIN t_item ti ON t.item_no = ti.itemID AND t.item_type = 't_item'
LEFT JOIN s_item si ON t.item_no = si.itemID AND t.item_type = 's_item';
这是sqlfiddle。
答案 2 :(得分:0)
你在这里:
(SELECT track.trackID, t_item.item_name FROM track
LEFT JOIN t_item ON track.item_no=t_item.itemID
WHERE track.item_type = 't_item')
UNION
(SELECT track.trackID, s_item.item_name FROM track
LEFT JOIN s_item ON track.item_no=s_item.itemID
WHERE track.item_type = 's_item')