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 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错