Question

I have this query:

    SELECT ava_users.*, 0 AS ord
    FROM ava_friend_requests
    LEFT JOIN ava_users 
    ON ava_friend_requests.from_user = ava_users.id
    WHERE ava_friend_requests.to_user = $user[id]
    UNION ALL
    SELECT ava_users.*, 1 AS ord
    FROM ava_friends
    LEFT JOIN ava_users 
    ON ava_friends.user2 = ava_users.id
    WHERE ava_friends.user1 = $user[id]
    ORDER BY ord
    LIMIT $from, $display_num

As you can see there are two queries with a UNION ALL.

Now my question is: How do I count EACH query? How can I retrieve each count value? I'd like to have a count result for query no 1 and a count result for query no2.

UPDATE: I would like to have a counting result like this: count 1: 34, count 2: 45

See here: select count from multiple tables

Was it helpful?

Solution

If you want to count the returned rows from the two subqueries, how about this:

SELECT 'Query1' as which, count(*) as cnt
FROM ava_friend_requests
LEFT JOIN ava_users 
ON ava_friend_requests.from_user = ava_users.id
WHERE ava_friend_requests.to_user = $user[id]
UNION ALL
SELECT 'Query2', count(*)
FROM ava_friends
LEFT JOIN ava_users 
ON ava_friends.user2 = ava_users.id
WHERE ava_friends.user1 = $user[id];

EDIT:

To do this after the limit, make the current query a subquery and do the counting:

select ord, count(*) as cnt
from (SELECT ava_users.*, 0 AS ord
      FROM ava_friend_requests
      LEFT JOIN ava_users 
      ON ava_friend_requests.from_user = ava_users.id
      WHERE ava_friend_requests.to_user = $user[id]
      UNION ALL
      SELECT ava_users.*, 1 AS ord
      FROM ava_friends
      LEFT JOIN ava_users 
      ON ava_friends.user2 = ava_users.id
      WHERE ava_friends.user1 = $user[id]
      ORDER BY ord
      LIMIT $from, $display_num
     ) t
group by ord;

It also might be easier just to count the ord column at the application level.

OTHER TIPS

You may want to try this:

select count(*) from (SELECT ava_users.*, 0 AS ord
FROM ava_friend_requests
LEFT JOIN ava_users 
ON ava_friend_requests.from_user = ava_users.id
WHERE ava_friend_requests.to_user = $user[id]
UNION ALL
SELECT ava_users.*, 1 AS ord
FROM ava_friends
LEFT JOIN ava_users 
ON ava_friends.user2 = ava_users.id
WHERE ava_friends.user1 = $user[id]
ORDER BY ord
LIMIT $from, $display_num) as users;

This means to deal with you union all like a table and count all the elements.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top