dqzlqfqeh845799833 2018-05-28 23:01 采纳率: 0%
浏览 104
已采纳

Mysql:只有子表有行时才从父表中选择

I need your help, How do I Select from a parent table, only if child table (another table that depends on id of parent table) has rows in php?

For instance: I have CATEGORY table and Items table. Where Category is the parent table and contains ct_id, ct_name, while Items is child table which contains it_id, ct_id (linked to parent table), it_name

PS: I don't need to select items, but I need only Categories ONLY if there are items linked to this table.

Thank you

  • 写回答

1条回答 默认 最新

  • douyan8266 2018-05-28 23:07
    关注

    You could use INNER JOIN which only returns records when there is a match on both tables.

    SELECT DISTINCT a.* FROM Categories a INNER JOIN Items b on b.ct_id = a.ct_id
    

    But it is more efficient to run a subquery:

    SELECT *
    FROM Categories 
    WHERE ct_id IN (SELECT ct_id FROM Items);
    

    This is because in the first example it has to match the entire table first and then strip out all the duplicates using the DISTINCT keyword. The second example avoids the duplication by scanning the child table first.

    This is known as a Semi Join. See here for more: https://dev.mysql.com/doc/refman/5.6/en/semi-joins.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器