如何消除连接sql语句中的重复结果
我有四个这样相关的表:
TABLE A: 1 to many with TABLE B
TABLE B: 1 to many with TABLE C
TABLE D: many to 1 with TABLE B
我想创建一个不包含重复项的结果集。
SELECT A.f1
A.f2
B.f1
C.f1
D.f1
from A LEFT JOIN (B INNER JOIN D on D.fk_b = B.id) on A.id = B.fk_a
LEFT JOIN C on C.fk_b = B.id
一些但不是所有记录都是重复的。仅TABLE D
中与TABLE B
具有相同FK 的记录。
如果有 2 个相同的 D.fk_B
字段,那么我只想选择第一个。我的 INNER JOIN
会变成这样:
B INNER JOIN TOP 1 D on.....
但这不可能?
谢谢你!
i have four tables which are related like this:
TABLE A: 1 to many with TABLE B
TABLE B: 1 to many with TABLE C
TABLE D: many to 1 with TABLE B
I would like to create a result set which contains no duplicates.
SELECT A.f1
A.f2
B.f1
C.f1
D.f1
from A LEFT JOIN (B INNER JOIN D on D.fk_b = B.id) on A.id = B.fk_a
LEFT JOIN C on C.fk_b = B.id
Some but not all records are duplicated. Only the records from TABLE D
which have the same FK to TABLE B
.
If there are 2 the same D.fk_B
fields then i would like to select only the first one. My INNER JOIN
would become something like:
B INNER JOIN TOP 1 D on.....
But that's not possible?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设所讨论的结构接近下图所示的结构,
以下 SELECT 语句将仅显示主键,简要介绍返回的数据。
现在您要求的选择:
上面的代码已经过测试并且在 MySQL 5.6 上运行良好
Assuming that the structure in question is near the one shown bellow,
The following SELECT statement will show you just the primary keys, briefly giving an idea about what data is being returned.
Now the select you've asked for:
Code above was tested and worked fine on MySQL 5.6
看来您有笛卡尔连接。
您可以尝试将 DISTINCT 放在列定义前面,或者可以使用子查询将表链接在一起。
It appears that you have cartesian join.
You could try just putting DISTINCT infront of you column definition or you could so subqueries to link the tables together.
尝试
你可以这样做:
像这样
尝试这个:
Try
You can do this:
Like this
Try this: