简体   繁体   中英

MySQL count rows from multiple tables using join

I have 3 MySQL tables:

**locations**
id      location_name
1       London
2       New York
3       Washington

**bookings**
id      voucher_code    location_id
1       DISC100         1
2       NULL            NULL
3       DISC200         1
4       DISC500         2
5       DISC700         1

**vouchers**
id      voucher_code    net_value
1       DISC100         155.00
2       DISC200         135.00
2       DISC500         155.00
2       DISC700         155.00

I'm trying to display a count of voucher net values for each location. So for example you can see that the 'London' location has 3 vouchers that have been redeemed in the bookings table, of which 2 were 155.00 values vouchers and one was 135.00. I need to write a MYSQL query to pull these counts out of the database.

So using the above tables as an example, my SQL query should result in the following:

Location            netValue155     netVaue135
London              2               1
New York            1               0
Washington          0               0

Below is what I have written so far:

select 
    l.location_name,
    '' as date_from, 
    '' as date_to,
    v.netValue155
from locations l 
left join (select voucher_code, count(distinct id) as netValue155 from vouchers where net_value='155.00' group by id) as v
select a.location_name, sum(netvalue155), sum(netvalue135) from
(select l.id ,l.location_name,
case when v.net_value = 155 then 1 else 0 end as netvalue155,
case when v.net_value = 135 then 1 else 0 end as netvalue135
from locations l left join bookings b
on l.id = b.location_id
left join vouchers v
on  b.voucher_code = v.voucher_code) a
right join locations l on l.id = a.id
group by a.location_name

[sql fiddle] http://sqlfiddle.com/#!9/daefd/19

You should do something like this:

SELECT 
    l.location_name AS Location,
    SUM(IF(v.net_value=155, 1, 0)) AS netValue155,
    SUM(IF(v.net_value=135, 1, 0)) AS netVaue135
FROM
    locations AS l
LEFT JOIN 
    bookings AS b ON (l.id = b.location_id)
LEFT JOIN 
    vouchers AS v ON (v.voucher_code = b.voucher_code)
GROUP BY 
    l.id

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