我有一个具有以下结构的表:
id name id_relation
---------------------------
1 this NULL
2 that 1
我想要一个查询而不是id_relation
来获取相关ID的名称(在这种情况下 - 'this',所以最后,我会得到这个结果:
id name parent_name
-----------------------
2 that this
是否可以这样做?
答案 0 :(得分:3)
是。加入表格:
select t1.id, t1.name, t2.name as parent_name
from mytable t1
left join mytable t2 on t2.id = t1.id_relation
where t1.id = 2; -- where clause is optional. leave off to get all rows
此查询将返回表中每一行的行,即使没有匹配的“关系”行。
如果您想将结果行限制为只有具有匹配行的行(如您的示例所示),请删除LEFT
关键字。
答案 1 :(得分:0)
你必须自己做一个表连接。就像是; select a.name, b.name from foo a, foo b where a.id_relation = b.id;