我是怎么用mysql COUNT()做的

时间:2013-02-17 13:37:30

标签: 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个结果。添加两个选择查询。

有人能告诉我怎么弄清楚这个吗?

想你。

2 个答案:

答案 0 :(得分:5)

使用子查询

包装UNION ed查询
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

答案 1 :(得分:3)

由于你在计算行数,所以不需要额外的sum + count + count开销。

这样做:

$q = "SELECT COUNT(*) FROM (
    SELECT 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 ALL
    SELECT 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%'
  ) mysubquery";