我有这张桌子:
// mytable
+----+---------+---------+
| id | related | color |
+----+---------+---------+
| 1 | NULL | red |
| 2 | 1 | blue |
| 3 | NULL | green |
| 4 | 1 | white |
| 5 | 3 | brown |
| 6 | NULL | gray |
| 7 | 3 | black |
| 8 | 1 | orange |
| 9 | 6 | pink |
+----+---------+---------+
我有id
个号码,我需要获得相关id
的颜色。
以下是一些例子:
$id = 4; // I need to get `red`
$id = 5; // I need to get `green`
$id = 6; // I need to get `gray`
$id = 9; // I need to get `gray`
这是我的疑问:
SELECT t2.color FROM mytable t1 JOIN mytable t2 ON t1.related = t2.id WHERE t1.id = :id
它几乎适用于所有行,并返回预期的颜色。只是它不适用于那些NULL
相关的行。我该如何解决这个问题?
答案 0 :(得分:2)
您可以使用LEFT JOIN
将相关颜色与相关列中的ID相关联。如果没有相关颜色,COALESCE()
将返回原色。
SELECT t.id, COALESCE(r.color,t.color) AS color
FROM myTable t
LEFT OUTER JOIN myTable r ON r.id = t.related
WHERE t.id = :id
以下是用于比较的INNER JOIN
查询。您会发现丢失了相关ID为NULL
的行,我不相信您想要的内容。
SELECT t.id, COALESCE(r.color,t.color) AS color
FROM myTable t
INNER JOIN myTable r ON r.id = t.related
WHERE t.id = :id
答案 1 :(得分:1)
SELECT c1.id as id,
IFNULL(c2.color, c1.color) as color
FROM colors c1
LEFT OUTER JOIN colors c2
ON c1.related = c2.id;
使用演示检查this sqlfiddle。