需要帮助编写查询
我有 2 个表 Table_A 和 Table_B。 Table_A 是Table_B 的父级。 Table_B 有 2 列引用 Table_A(我的意思是这两列都引用父级中的列)。
Table_A 包含以下列(id、name、className) Table_B 包含以下列(源、目标),两列均引用 Table_A 中的 id
假设 Table_A
包含以下数据
id name className
---------------------------
1 N1 C1
2 N2 C2
3 N3 C3
4 N4 C4
5 N5 C6
Table_B
Source Destination
------------------
1 2
2 3
3 4
3 5
我需要一个查询,其中需要存在于中的所有 Id目标而不是源,我需要将此 Id 与 Table_A
连接以获取名称和类名。
对于我显示的数据,查询应检索以下行。
4 N4 C4
5 N5 C5
顺便说一句,我在这里显示了部分数据,但 Table_B
有超过 1000 条记录。
编辑
我编写了以下查询,但它显示了错误的结果
select * from Table_A where id not in (select distinct Source from Table_B)
,但它目前给出了正确的结果,但从长远来看,我们可能会面临性能问题,并且查询检索源和目标中都不存在的数据。
I have 2 tables Table_A and Table_B. Table_A is a parent of Table_B. Table_B has 2 columns which refer to Table_A(I Mean both the columns refer to a column in Parent).
Table_A contains following columns (id,name,className)
Table_B contains following column (source,destination) both the columns refer to id in Table_A
Assume that Table_A
contains the following data
id name className
---------------------------
1 N1 C1
2 N2 C2
3 N3 C3
4 N4 C4
5 N5 C6
Table_B
Source Destination
------------------
1 2
2 3
3 4
3 5
I need a query where I require all Ids present in the Destination and not in Source and I need to join this Ids with Table_A
to get name and className.
For the data I have shown the query should retrieve the following rows.
4 N4 C4
5 N5 C5
BTW here I have shown partial data but Table_B
has more than 1000 records.
EDIT
I have written the following query but it was showing wrong results
select * from Table_A where id not in (select distinct Source from Table_B)
But it was giving right results currently but on long run we may face performance issue and also query retrieves data which is not present in both Source and Destination.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我只安装了 SQLite,但这个简短的查询完成了这项工作:
编辑: 当然,看到与其他解决方案的性能比较会很有趣。
I only have SQLite installed, but this short query did the job:
EDIT: Of course it would be interesting to see a performance comparison with other solutions.
您需要将问题分成两部分,第一部分是获取不在源中的目标,第二部分是连接两个表。
要获取不在源代码中的目标,类似这样的事情应该可以工作:
然后我们需要的是联接,所以
我不能保证这是正确的,因为我目前无法访问数据库或查询分析器,但它应该让你走上正轨。
You need to split your problem into two parts, the first is getting the Destinations that are not in source, the second is joining the two tables.
To get the Destinations which aren't in source, something like this should work:
Then what we need is the join, so
I cant gaurnetee this is correct as I dont have access to a database or query analyzer at the moment, but it should put you on the right track.