dsfhe34889789708 2017-05-22 12:26
浏览 34
已采纳

SQL - 如果存在于另一个表中

There are 2 tables: subjects and messages.

subjects table:

----id----   ----title----
1            Subject 1
2            Subject 2
3            Subject 3

messages table:

----id----   ----subject----   ----message----
1            1                 Message to Subject 1
2            1                 Message to Subject 1
3            2                 Message to Subject 2

How to get mysql_num_rows of subjects, which has got any messages in messages? The result must be 2, because Subject 1 has message in messages, and Subject 2 has message in messages, but Subject 3 hasn't got any message in messages.

Something like:

mysql_num_rows(mysql_query("SELECT * FROM subjects ...

  • 写回答

4条回答 默认 最新

  • dsedug8644 2017-05-22 12:30
    关注

    You would normally use in or exists for this purpose:

    select count(*)
    from subjects s
    where exists (select 1 from messages m where m.subject_id = s.id);
    

    This can easily be modified to get the subjects with no messages.

    If you have a proper foreign key relationship defined between the tables, then you can just count the subjects in messages:

    select count(distinct m.subject_id)
    from messages;
    

    Aggregation in MySQL is quite expensive. There are circumstances where this will perform better. However, the existsis likely to perform better under most circumstances, assuming you have an index onmessages(subject_id)`.

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

报告相同问题?

悬赏问题

  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理