我有一张表,有4列:id, name, to_id, to_id2
SELECT id, name, (name WHERE to_id=id) as to1, (name WHERE to_id2=id) as to2 FROM table
我想以某种方式显示名称而不是to_id和to_id2。此代码:SELECT id, name, to_id, to_id2 FROM TABLE
将to_id,to_id2作为数字,因为它们是id-s。
答案 0 :(得分:3)
使用CASE WHEN ... THEN ... END
:
SELECT id, name,
(CASE WHEN to_id = id THEN name ELSE NULL END) as "t1",
(CASE WHEN to_id2 = id THEN name ELSE NULL END) as "t2"
FROM `your_table`
您可以详细了解case
声明here。
答案 1 :(得分:1)
你必须使用JOIN
,试试这个:
SELECT t1.id, t1.name, t2.name as t2Name, t3.name as t3Name
FROM tbl t1
LEFT JOIN tbl t2 ON t1.to_id = t2.id
LEFT JOIN tbl t3 ON t1.to_id2 = t3.id