douci1677 2012-11-30 02:36
浏览 42
已采纳

无法弄清楚如何从查询中获得我想要的结果

I'm new to databases and mysql. I'm having a difficult time even deciding exactly what the problem I'm facing is and don't really know what the relevant google search would be. So forgive me if this is a mind-blowingly retarded question. I have two tables tabs and cats.

tabs is like this:

name | order
tab1 | 3
tab2 | 0
tab3 | 1
tab4 | 2

cats is like this:

name | tab_name
cat1 | tab3
cat2 | tab3
cat3 | tab1
cat4 | tab1
cat5 | tab1

I guess it's a one-to-many relationship tabs-to-cats. My question is how can I structure a query that will return only distinct tab names, each with all of its associated cats? I can get a result with all the cats and many duplicate tabs. Or I can get only distinct tabs but only one cat per tab. Maybe I should just be testing for duplicate tabs with my php code? Or querying tabs then querying all the cats for each tab? It just seems like there has got to be a more direct way. I'm currently using this query:

SELECT t.name AS tab, c.name AS cat FROM tabs t
LEFT JOIN categories c
ON t.name=c.tab_name
ORDER BY t.order;
  • 写回答

2条回答 默认 最新

  • dongyuan9149 2012-11-30 02:40
    关注

    You can use MySQL's GROUP_CONCAT() to produce a comma-separated list of cat, if that is what you want:

    SELECT
      t.name AS tab,
      GROUP_CONCAT(c.name) AS cats
    FROM 
      tabs t 
      LEFT JOIN categories c ON t.name = c.tab_name
    GROUP BY tab
    ORDER BY t.`order`   /* ORDER is a reserved keyword and has to be quoted as `order` */
    

    This would produce output like:

    tab      cats
    ------------------------------
    Tab1     Cat1,Cat2,Cat3,Cat4
    Tab2     Cat4,Cat3,Cat6,Cat7
    

    However,

    the query you have which produces multiple rows per tab is a more conventional way to handle this. In your application code, you would loop over the tab cat pairs and test for a change of the tab. If you use the GROUP_CONCAT() above, you would also need to split it on the , in your application code.

    Either way, you cannot get a hierarchical result row-wise in the SQL - you have to repeat tab for each row. That's just the nature of the 2-dimensional structure of a result set. So it will require some application-side processing.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂