dongxia2068 2016-05-29 14:20
浏览 19
已采纳

Mysql查询里面的查询

First, apologies if the title doesn't match the question. Well, the problem is how to build this query...

I have a table called category It contains categories of my stuff(movies). It's like this...

--------------------------------
ID | name   | parent_category
--------------------------------
1  | love   | 0
2  | action | 0
3  | fear   | 0
4  | passion| 1
5  | danger | 2
6  | death  | 3
--------------------------------

So, as you see, each category has a parent category. Except the first 3. They're parents.

And movies table is like this...

--------------------------------
ID | name   | category
--------------------------------
1  | aaaa   | 1
2  | bbbbbb | 2
3  | cccc   | 2
4  | ddddddd| 1
5  | eeeeee | 3
6  | fffff  | 3
--------------------------------

So, what i want to do is, to select movies by parent category. Which means if I click category, love, it should select all the movies of categories that having love as the parent category.

So, how to write this in a single query ?

  • 写回答

3条回答 默认 最新

  • dto5637 2016-05-29 14:29
    关注

    If the parents are only one level deep, then you can use joins:

    select m.*,
           coalesce(cp.id, c.id) as parent_id,
           coalesce(cp.name, c.name) as parent_name
    from movies m left join
         categories c
         on m.category = c.id left join
         categories cp
         on c.parent_category = cp.id;
    

    Actually, if you only want the id, you don't need two joins:

    select m.*,
           (case when c.parent_id > 0 then c.parent_id else c.id end) as parent_id
    from movies m left join
         categories c
         on m.category = c.id ;
    

    Or, more simply:

    select m.*, greatest(c.parent_id, c.id) as parent_id
    . . .
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器