繁体   English   中英

SQL连接用于选择两个具有公共数据的记录

[英]SQL join for selecting two records with common data

我有具有此类记录的数据库:

Id     | Value  | DocId |
------ | ------ | ------|
1      |  10    |  null |
2      | -10    |  1    |  //this is child of record with id = 1
3      |  15    |  null |
4      | -15    |  3    |  //this is child of record with id = 3
5      |  7     |  null |
6      | -7     |  5    |  //this is child of record with id = 5 
7      | 16     |  null |

所以我想选择Id = 1Id = DocId ,因此应该返回(因为这些是Id = 1DocId = 1

Id     | Value  | DocId |
------ | ------ | ------|
1      | 10     |  null |
2      | -10    |  1    |

我知道我可以使用where子句,但是我需要使用Join来完成。

您可以从同一张表中选择两次,就像它们是两个单独的表一样:

从TheTable t1,theTable t2中选择*,其中t1.id = t2.DocId;

您正在显示where id = 1 or docid = 1 那么,为什么必须使用联接呢? 这似乎没有道理。 无论如何,您可以在这里:

select t.*
from t
join (select 1 as id) x on x.id in (t.id, t.docid);

您说的是您想要id = 1或docId = 1的记录。因此在sql中,您几乎可以这样说:

select * from my_table where id = 1 or docId = 1;

暂无
暂无

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

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