How to select related row when current row is empty?

不羁的心 提交于 2019-12-13 07:17:38

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!