复杂的mysql查询与表连接

时间:2014-01-21 07:22:58

标签: mysql join

我有一个处理复杂JOIN查询的任务。

Tabel 1:object_category (树状结构,将父类别设置为子类别层次结构)

----------------------
category_id parent_id
----------------------
1           null
2           null
3           1
4           1
5           2
6           2
----------------------

注意类别3是1的孩子,5是2的孩子等等。

表2:object_category_map (使用object_category表的category_id映射object_id的表)

----------------------
object_id  category_id
----------------------
23          1
23          4
23          6
24          2
24          5
----------------------

任务是找到没有为category_id映射parent_id的object_id。

例1: object_id:24,category_id:2,5 在表2中,object_id 24关联category_id 5,而parent_id为5,它是2,

例2: object_id:23,category_id:1,4,6 object_id 23 miss_id 6的miss_id(2)。

任务是从table2中找到23是object_id的列表,其类似于23.

请帮助解决这个问题。感谢。

1 个答案:

答案 0 :(得分:1)

你可以尝试这样的事吗。

select object_parent_needed.object_id
from (
    select object_id,object_category_map.category_id,parent_id
    from object_category_map 
    join object_category on object_category_map.categor_id = object_category.category_id
    where parent_id is not null
) object_parent_needed
left outer join object_category_map on object_category_map.object_id = object_parent_needed.object_id  
                                    and object_category_map.category_id = object_parent_needed.parent_id
where object_category_map.category_id is null