Jump to content

Crazy GROUP / UNION ALL


unemployment

Recommended Posts

Table Name: partners

 

partner_id user_id friend_id approved

      8               3       2       1

    11               1       3       1

 

I need to write a mysql query that sum's the total of partners each userid has. 

 

In this example, user_id 3 would have 2 friends, user_id 1 would have 1 friend and user_id 2(located as a friend_id) would have 1 friend.

Link to comment
Share on other sites

If you are looking for the count for an individual user (say ID 3), I would use something like this:

 

SELECT COUNT(*) AS Cnt FROM partners WHERE 3 IN (user_id, friend_id);

This is going to do a table scan.

 

If you are looking for the count for ALL users, I would try something like this:

 

SELECT user_id, SUM(Cnt) AS Total FROM (
SELECT user_id, count(*) AS Cnt FROM partners GROUP BY user_id
UNION ALL
SELECT friend_id, count(*) FROM partners GROUP BY friend_id
) AS U
GROUP BY user_id;

This may do two table scans; or, if user_id and friend_id are both individual indexes, this may just scan the indexes.

 

If you are looking for an individual user and don't want to do a table scan; if user_id and friend_id are indexes, use the second query but with a WHERE clause inside and no need for the GROUP BY:

SELECT SUM(Cnt) AS Total FROM (
SELECT count(*) AS Cnt FROM partners WHERE user_id = 3
UNION ALL
SELECT count(*) FROM partners WHERE friend_id = 3
) AS U;

 

Of course, this requires version 5.something of mySql to use the SELECT as a psuedo table.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.