多对多查询mysql返回重复行

时间:2014-02-10 13:41:58

标签: php mysql sql many-to-many relational-database

我有2张桌子

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)相关的所有资源的资源。*,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因为它写了一个temp。我的表现很慢的表。

感谢

2 个答案:

答案 0 :(得分:1)

可能改为使用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

答案 1 :(得分:0)

你的连接条件错误,因为它与son元素匹配,即使父元素是你需要的元素。

SELECT l.id as link_id,r.* 
FROM `resources` as r
CROSS JOIN res_res as l
WHERE (l.parent_id = 2 AND l.parent_id=r.id) OR (l.son_id = 2 AND l.son_id=r.id)