TNK
TNK

Reputation: 4323

How I do this with mysql COUNT()

I am using this UNION query to count the records the query give.

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.

Can anybody tell me how I figure out this?

Think you.

Upvotes: 1

Views: 92

Answers (2)

Sebas
Sebas

Reputation: 21532

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";

Upvotes: 3

John Woo
John Woo

Reputation: 263723

wrap the UNIONed query with subquery

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

Upvotes: 5

Related Questions