查询以显示值的名称而不是来自一个 table 的 ID
Query to display name for value instead of ID from one table
在此 table 中是一个个人列表,其中一些个人是 parent 另一个人,在 parentID1
和 parentID2
列中指定为personID
仅值。我想在第一列中显示个人列表,然后在第二列中显示他们 parent 的姓名。
您可以自行加入 table 两次:
select
t.name,
t1.name parentName1,
t2.name parentName2
from mytable t
left join mytable t1 on t1.personID = t.parentID1
left join mytable t2 on t2.personID = t.parentID2
或者您可以使用内联相关子查询:
select
t.name
(select t1.name from mytable t1 where t1.personID = t.parentID1) parentName1,
(select t1.name from mytable t2 where t2.personID = t.parentID2) parentName2
from mytable t
这假定在 table 中不会有超过 1 条记录具有匹配给定 parentID1
或 parentID2
的 personID
(否则查询将失败,因为内联子查询将 return 多条记录)。
您好,请尝试使用如下查询中的自连接功能。请试试这个
select t.name,
from tableName1 as t1,tableName1 as t2
where t1.personID=t2.parentID1
在此 table 中是一个个人列表,其中一些个人是 parent 另一个人,在 parentID1
和 parentID2
列中指定为personID
仅值。我想在第一列中显示个人列表,然后在第二列中显示他们 parent 的姓名。
您可以自行加入 table 两次:
select
t.name,
t1.name parentName1,
t2.name parentName2
from mytable t
left join mytable t1 on t1.personID = t.parentID1
left join mytable t2 on t2.personID = t.parentID2
或者您可以使用内联相关子查询:
select
t.name
(select t1.name from mytable t1 where t1.personID = t.parentID1) parentName1,
(select t1.name from mytable t2 where t2.personID = t.parentID2) parentName2
from mytable t
这假定在 table 中不会有超过 1 条记录具有匹配给定 parentID1
或 parentID2
的 personID
(否则查询将失败,因为内联子查询将 return 多条记录)。
您好,请尝试使用如下查询中的自连接功能。请试试这个
select t.name,
from tableName1 as t1,tableName1 as t2
where t1.personID=t2.parentID1