Home » Php » php – SQL query to return combined data of all rows that don't belong to current user

php – SQL query to return combined data of all rows that don't belong to current user

Posted by: admin February 25, 2020 Leave a comment

Questions:

Imagine this is my table:

----------------------------------------------------
| id | user_id    | amount_1 | amount_2 | amount_3 |
----------------------------------------------------
| 1  | 1          | 2        | 3        | 4        |
----------------------------------------------------
| 2  | 2          | 2        | 1        | 1        |
----------------------------------------------------
| 3  | 2          | 1        | 2        | 2        |
----------------------------------------------------
| 4  | 3          | 2        | 1        | 4        |
----------------------------------------------------

I need a query that gives me one result set for every entry that belongs to my current user, and then returns everything else as a single combined row with the amounts summed.

So in this case if I am user 1, I should get the following rows back:

---------------------------------------
| id | amount_1 | amount_2 | amount_3 |
---------------------------------------
| 1  | 2        | 3        | 4        |   my own amounts
---------------------------------------
| 2  | 5        | 4        | 7        |   everyone else's amounts
---------------------------------------

Any tips?

I’ve considered it might be a better idea to just filter the data in the code (php). Please help i’m starting to hate myself

How to&Answers:

You can do with one query using union:

SELECT user_id, amount_1, amount_2, amount_3
    FROM table
    WHERE user_id = YOUR_USER_ID
UNION
SELECT -1, SUM(amount_1) AS amount_1, SUM(amount_2) AS amount_2, SUM(amount_3) AS amount_3
    FROM table
    WHERE user_id != YOUR_USER_ID

Answer:

You could use a UNION in sql

select 1 id, amount_1, amount_2, amount_3 
from my_table 
where user_id = 1 
union  
select 2  , sum(amount_1) , sum(amount_2), sum(amount_3 )
from my_table 
where user_id <> 1 

Answer:

You can use aggregation in one fell swoop:

select (case when user_id = 1 then id end) as my_user_or_not,
       sum(amount_1), sum(amount_2), sum(amount_3)
from t
group by my_user_or_not;

The null values in the first column indicate another user. You have labelled the column id, which is a bit problematic if you were — for instance — to choose user_id = 2 in your example. NULL seems safer for this purpose.