[英]How I do this with mysql COUNT()
I am using this UNION query to count the records the query give. 我正在使用此UNION查询来计算查询提供的记录。
This is my query: 这是我的查询:
// 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%'";
After executing this query I got below result as my output. 执行此查询后,我得到以下结果作为输出。
+---------------------------------+
| COUNT( DISTINCT i.institute_id) |
+---------------------------------+
| 3 |
| 2 |
+---------------------------------+
This is not my expecting result. 这不是我的预期结果。 I need to get 5 as the result by adding 3 + 2. With adding two select query. 我需要通过添加3 + 2得到5作为结果。添加两个select查询。
Can anybody tell me how I figure out this? 有人可以告诉我如何解决吗?
Think you. 想你。
wrap the UNION
ed query with subquery 用子查询包装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
Since you're counting the rows, there's no need of additional overhead of sum + count + count. 由于您要对行进行计数,因此不需要额外的总和+计数+计数开销。
Just do this: 只要这样做:
$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";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.