简体   繁体   中英

How to join 3 tables to a single table in SQL

I need to join 3 tables to a single table. Here is the scenario.

Table 1: Has user_id, app_id

Table 2: Has user_id, gender

Table 3: Has app_id, app_name(PC, Mobile)

Table 4: Has user_id, user_city

Now I am looking to get a count of users by mobile male, mobile female, pc male, pc female grouped by cities.

Here is my SQL. However, I guess I am doing it wrong with the joins. Please correct me.

SELECT
    t4.user_city,
    sum(case when t2.gender = 'm' and t3.app_name = 'PC' then 1 else 0 end) pcmale,
    sum(case when t2.gender = 'f' and t3.app_name = 'PC' then 1 else 0 end) pcfemale,
    sum(case when t2.gender = 'm' and t3.app_name = 'Mobile' then 1 else 0 end) mobilemale,
    sum(case when t2.gender = 'm' and t3.app_name = 'Mobile' then 1 else 0 end) mobilefemale,
FROM
    table1 t1
    inner join
    table2 t2 on t1.user_id = t2.user_id
    inner join
    table3 t3 on t1.app_id = t3.app_id
    inner join
    table4 t4 on t1.user_id = t4.user_id
GROUP BY 1

Can we join multiple tables to a single table in the way i have done in my query. Please help

Yes. Your joins are correct as written.

If there is a value in T1 that is not present in T2, T3, or T4 it will be excluded from your results. This is because the JOIN you have written is an INTERSECTION . For example, if a row in T1 had a value for app_id = '99' and T2 did not have a corresponding value of '99' for app_id than it would not be returned in the SQL you have written.

In those situations if you would like to return the row in T1 containing 'u' you will need to write a 'LEFT OUTER JOIN' which returns all records from the LEFT table and matching records from the RIGHT table. For example, T1 having a value of '99' for app_id you would get a NULL value for app_name in T3.

This is an overly simplified example of the JOIN logic in a query but it hopefully it's helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM