Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join these tables?

Tags:

mysql

I have three tables in a database, as follows:

users:

  user_id                     name              pbal

    1                          m1               100
    2                          m2               200
    3                          m3               300
    4                          m4               400
    5                          m5               500

payouts:

    id                       user_id           amount

    1                          1                100
    2                          1                200
    3                          2                300
    4                          1                400

blocked:

   id                          user_id           status
 ------                        --------          ------
    1                           2                 block
    2                           3                 block

Now I want to make a list that excludes users whose user_id is in the blocked table, and that calculates a new total amount based on the pbal from users and the amount from the related rows in payouts:

   name                 total_amount
   -----                ------------
    m1                    800
    m5                    500
    m4                    400

I have been trying for half an hour, but failed. Can someone help me?

like image 1000
Maksud Masum Avatar asked Jun 08 '18 16:06

Maksud Masum


People also ask

How do you join tables?

The join is done by the JOIN operator. In the FROM clause, the name of the first table ( product ) is followed by a JOIN keyword then by the name of the second table ( category ). This is then followed by the keyword ON and by the condition for joining the rows from the different tables.

How do I join 4 tables in SQL query?

Create a table2 for the professor details as p_details using SQL query as follows. Create a table for subjects as subjects using SQL query as follows. Create a table for the subject marks details using SQL query as follows. CREATE TABLE marks_details ( total_marks INT(5) PRIMARY KEY, theory INT(5), practical INT(5) );

What are the 4 different table joining types?

Four types of joins: left, right, inner, and outer.

What are the 5 different types of tables joins?

As known, there are five types of join operations: Inner, Left, Right, Full and Cross joins.


1 Answers

Here's an example:

SELECT u.name, u.user_id, MAX(u.pbal) + SUM(p.amount) AS total_amount
FROM dbo.Payouts p 
INNER JOIN dbo.Users u ON u.user_id = p.user_id
LEFT OUTER JOIN dbo.Blocked b ON u.user_id = b.user_id
WHERE b.user_id IS NULL
GROUP BY u.user_id, u.name
ORDER BY MAX(u.pbal) + SUM(p.amount) DESC;
like image 134
Brent Ozar Avatar answered Nov 02 '22 23:11

Brent Ozar