我正在使用这个 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 作为结果。添加两个选择查询。
谁能告诉我我是怎么弄明白的?
想想你。
最佳答案
用子查询包装 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
关于php - 我如何使用 mysql COUNT() 执行此操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14921663/