php - 我如何使用 mysql COUNT() 执行此操作

标签 php mysql sql

我正在使用这个 UNION 查询来计算查询给出的记录。

这是我的查询:

// Count the number of records:
$q = "SELECT COUNT( DISTINCT i.institute_id)    
          FROM institutes AS i
            INNER JOIN institute_category_subject AS ics 
                ON ics.institute_id = i.institute_id
            INNER JOIN subjects AS s 
                ON ics.subject_id = s.subject_id
          WHERE s.subject_name LIKE '%mathematics%'
        UNION
        SELECT COUNT( DISTINCT t.tutor_id)
          FROM tutors AS t
            INNER JOIN tutor_category_subject  AS tcs
                ON tcs.tutor_id = t.tutor_id
            INNER JOIN subjects AS s
                ON tcs.subject_id = s.subject_id
          WHERE s.subject_name LIKE '%mathematics%'";

执行此查询后,我的输出结果如下。

+---------------------------------+
| COUNT( DISTINCT i.institute_id) |
+---------------------------------+
|                               3 |
|                               2 |
+---------------------------------+

这不是我期望的结果。我需要通过添加 3 + 2 得到 5 作为结果。添加两个选择查询。

谁能告诉我我是怎么弄明白的?

想想你。

最佳答案

用子查询包装 UNIONed 查询

SELECT SUM(total) totalSum
FROM
    (
        SELECT  COUNT( DISTINCT i.institute_id) total
        FROM    institutes AS i
                INNER JOIN institute_category_subject AS ics 
                    ON ics.institute_id = i.institute_id
                INNER JOIN subjects AS s 
                    ON ics.subject_id = s.subject_id
        WHERE   s.subject_name LIKE '%mathematics%'
        UNION
        SELECT  COUNT( DISTINCT t.tutor_id)   total
        FROM    tutors AS t
                INNER JOIN tutor_category_subject  AS tcs
                    ON tcs.tutor_id = t.tutor_id
                INNER JOIN subjects AS s
                    ON tcs.subject_id = s.subject_id
        WHERE   s.subject_name LIKE '%mathematics%'
    ) s

关于php - 我如何使用 mysql COUNT() 执行此操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14921663/

相关文章:

javascript - 如何将 Yoast wordpress 插件添加到 laravel

php - 使用参数替换准备语句的 mysql 字段名

php - Mysql 获取上一个日期记录时出错

mysql - 第 1 行的错误 13 (HY000) : Can't get stat of (Errcode: 13)

php - Laravel 尝试输出帖子,但 Controller 功能似乎工作不正常

php - JavaScript 和 PHP 可以证明在线纸牌游戏吗?

php - 如何搜索多个字段(SQL、PHP)?

mysql 选择唯一行

mysql - 如何从 A 表中选择 B 表中不存在的值?

SQL: JOIN 与 'near' 匹配