我有 2 张 table
1 个资源
id | name | type
1 | X | form
2 | YY | post
3 | ZZ | container
2 res_res
id | parent_id | son_id
1 | 1 | 2
2 | 3 | 1
现在我想选择与资源id(1)相关的所有资源的resource.*,res_res.id
预期结果
link_id | id | name | type |
1 | 2 | YY | post |
2 | 3 | ZZ | container
我的查询
1:
SELECT distinct r.* FROM `resources` as r
join res_res as l on (l.parent_id=r.id or l.son_id=r.id)
where l.parent_id = 2 or l.son_id = 2
此查询按预期运行并返回我想要的结果,只是它不包含 id 或链接(来自 resource_resource 表的 id),但如果我运行此查询
2:
SELECT distinct l.id as link_id,r.* FROM `resources` as r
join res_res as l on (l.parent_id=r.id or l.son_id=r.id)
where l.parent_id = 2 or l.son_id = 2
这会返回很多重复的行;那么我做错了什么?
我认为问题是我的连接条件在行匹配时同时返回parent-id和son-id,所以会发生重复,我需要在select中放置一个if case,以便我只选择其他字段。
有没有更好的方法来选择与resource.id X相关的所有资源并包含加入id?
我不喜欢使用 group_by 因为它会写入一个临时值。表这大大降低了我的性能。
谢谢
最佳答案
可能使用 UNION 来代替:-
SELECT l.id AS link_id, l.son_id AS id, r.name, r.type
FROM `resources` AS r
INNER JOIN res_res AS l ON l.parent_id = r.id
WHERE l.son_id = 1
UNION
SELECT l.id AS link_id, l.parent_id AS id, r.name, r.type
FROM `resources` AS r
INNER JOIN res_res AS l ON l.son_id = r.id
WHERE l.parent_id = 1
关于php - 多对多查询mysql返回重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21678839/