[英]MySQL referring to own id from within table
I have a table with two id
columns and a name
column the first of the id
columns is the primary key, the second either refers to a primary key or is NULL. 我有两个表id
列和一个name
列中的第一个的id
列是主密钥,第二或者是指主键或为空。
+--+-----+----+
|id|subid|name|
+--+-----+----+
|1 |NULL |Tom |
+--+-----+----+
|2 |1 |Will|
+--+-----+----+
Given a name, I would like to, using only one SQL
statement to output all entries with that given name, but if the secondary id
field refers to a primary key, to output that entry instead. 给定名称,我想仅使用一条SQL
语句输出具有该给定名称的所有条目,但是如果辅助id
字段引用主键,则改为输出该条目。
Using the above example if I input "Tom" I would like to output name
= "Tom" and if I input "Will" I would like to output name
= "Tom" too? 使用上面的示例,如果我输入“ Tom”,我想输出name
=“ Tom”,如果我输入“ Will”,我也想输出name
=“ Tom”?
Is that achievable with one SQL statement only, because I would like to avoid looping through results. 仅通过一条SQL语句就能做到这一点,因为我想避免循环遍历结果。
Yes. 是。 You want to use a join
for this and an expression in the select
: 您要为此使用join
,并在select
使用表达式:
select t.*
from table t left outer join
table sub
on t.subid = sub.id
where 'Tom' = t.name or 'Tom' = sub.name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.