简体   繁体   中英

Joining Two tables Based on Third Table (SQLite)

I'm trying to use three different tables to get a list of all McDonald's in the US, sorted by number of Burger Kings within 100 miles. For some reason, I'm having a really hard time wrapping my head around this problem, and I'm wondering if anyone can offer any suggestions on how they might approach a problem like this?

I have a table of all McDonald's with their zip codes, a table of all zip codes with number of burger kings, and a table of all zip codes within 100 miles of each other. For example:

Mcdonalds table:

NAME zip
McDonalds Park Terrace 11121
McDonalds HWY 103 11412
McDonalds Crestwood 11121
McDonalds Pendleton 26566
McDonalds Smithville 67742
McDonalds HWY 66 43351

BKzips table:

zip numberBKs
11121 2
11412 0
26566 6
43351 0
67742 3
... ...

zipproximity table:

zip1 zip2 distancebetween
11121 11412 23.443
11121 26566 48.211
... ... ...
11412 11121 23.443

My desired end result is a table with a row for each mcdonalds, listing all zips within 100 mi of that mcdonalds and their total number of BKs. For example:

McDonalds zip zipsWithBKs totalBKs
McDonalds Park Terrace 11121 26566, 11412 6

I've been able to use inner joins to get a table with one row per zip with BKs:

SELECT McDonalds.NAME, BKzips.zip, BKzips.numberBKs
FROM zipproximity
    INNER JOIN McDonalds
        ON zipproximity.zip1 = McDonalds.zip
    INNER JOIN BKzips 
        ON zipproximity.zip2 = BKzips.zip

But I can't figure out how to get my desired result. Between not being experienced with SQL and working this problem for hours I'm pretty stuck. I appreciate any help!

Nearly there, just a GROUP BY and some aggregation functions:

SELECT McDonalds.NAME, McDonalds.zip, GROUP_CONCAT(BKzips.zip, ', ') AS zipsWithBKs, SUM(BKzips.numberBKs) AS totalBKs
FROM zipproximity
    INNER JOIN McDonalds
        ON zipproximity.zip1 = McDonalds.zip
    INNER JOIN BKzips 
        ON zipproximity.zip2 = BKzips.zip
-- WHERE BKzips.numberBKs > 0   -- you probably want this also
GROUP BY McDonalds.NAME, McDonalds.zip;

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