1

我正在使用这个 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 作为结果。添加两个选择查询。

谁能告诉我我是怎么想出来的?

想你。

4

2 回答 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
于 2013-02-17T13:39:04.050 回答
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";
于 2013-02-17T13:41:36.763 回答