I have a table, with 4 column: 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
I would like to show somehow the names instead of the to_id and to_id2. This code: SELECT id, name, to_id, to_id2 FROM TABLE
give to_id, to_id2 as a number, because they are id-s.
You have to use JOIN
, try this:
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
Use 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`
You can learn more about case
statement here.