简体   繁体   English

如果只有一行结果,则选择自我连接

[英]select self join if only one resulting row

Is it possible/economical to perform a SELF JOIN of a table (for this example, my table called myTable has two columns pk and fk ), and return a record if there is only one resulting record? 对表执行SELF JOIN是否可行/经济(对于本示例,我的表myTable有两列pkfk ),如果只有一个结果记录,则返回一条记录? I am thinking of something like the following, however, only_one_row() is a fictional function that would need to be replaced with something real: 我正在考虑类似以下的内容,但是only_one_row()是一个虚构的函数,需要将其替换为真实的东西:

SELECT fk
FROM myTable as t1
INNER JOIN myTable AS t2 ON t2.fk=t1.fk
WHERE t1.pk=1
AND only_one_row();

For instance, if myTable(id,fk) had the following records, only one record is produced, and I which to select the record: 例如,如果myTable(id,fk)具有以下记录,则仅生成一个记录,而我选择该记录:

1 1
2 1
3 2

However, if myTable(id,fk) had the following records, two '1' records are produced, and the select should not return any rows: 但是,如果myTable(id,fk)具有以下记录,则会生成两个“ 1”记录,并且select不应返回任何行:

1 1
2 1
3 2
4 1

I could use PHP to do so, but would rather just use SQL if feasible. 我可以使用PHP来这样做,但如果可行的话,宁愿只使用SQL。

Use a HAVING clause that counts the results. 使用对结果进行计数的HAVING子句。

SELECT fk
FROM myTable as t1
INNER JOIN myTable AS t2 ON t2.fk=t1.fk
WHERE t1.pk=1
HAVING COUNT(*) = 1

How about this: 这个怎么样:

SELECT fk
FROM myTable as t1
INNER JOIN myTable AS t2 ON t2.fk=t1.fk
WHERE t1.pk=1
GROUP BY fk
HAVING COUNT(fk) = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM