问题
I have a table like this:
// mytable
+----+---------+---------+
| id | name | related |
+----+---------+---------+
| 1 | Jack | 1 |
| 2 | | 1 |
| 3 | | 1 |
| 4 | | 2 |
| 5 | peter | 2 |
| 6 | peter | 2 |
| 7 | | 2 |
| 8 | jhon | 4 |
| 9 | | 3 |
| 19 | ali | 3 |
| 20 | | 4 |
| 21 | | 4 |
+----+---------+---------+
All I have is a id-number, Here is my query:
SELECT name FROM mytable WHERE id = :id LIMIT 1
In my query sometimes name
is empty. So I'm trying to select related name, how can I do that?
Here is some example: (plus expected output)
:id = 1
+---------+
| Jack |
+---------+
:id = 2
+---------+
| Jack |
+---------+
:id = 21
+---------+
| jhon |
+---------+
:id = 6
+---------+
| peter |
+---------+
回答1:
The query below will work with ids 1, 2 and 6. I'm not sure how to get id 21 to equal jhon. If I join the table four times I get to Jack. I hope this helps.
SELECT (CASE WHEN A.name IS NULL THEN B.name ELSE A.name END)
FROM mytable A LEFT JOIN mytable B ON (A.related=B.id)
来源:https://stackoverflow.com/questions/37259513/how-to-select-related-row-when-current-row-is-empty