[英]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.我正在尝试使用三个不同的表格来获取美国所有麦当劳的列表,按 100 英里内的汉堡王数量排序。 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.我有一张包含所有麦当劳 zip 代码的表格,一张包含所有 zip 代码的表格以及汉堡王数量的表格,以及一张包含所有 zip 代码的表格,这些代码在 100 英里范围内。 For example:
例如:
Mcdonalds
table: Mcdonalds
表:
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: BKzips
表:
zip ![]() |
numberBKs![]() |
---|---|
11121 ![]() |
2 ![]() |
11412 ![]() |
0 ![]() |
26566 ![]() |
6 ![]() |
43351 ![]() |
0 ![]() |
67742 ![]() |
3 ![]() |
... ![]() |
... ![]() |
zipproximity
table: zipproximity
表:
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.我想要的最终结果是一个表格,每个麦当劳都有一行,列出了麦当劳 100 英里内的所有拉链及其 BK 总数。 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:我已经能够使用内部连接来获得一个表,其中每个 zip 带有 BK:
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.
在没有 SQL 经验和解决这个问题几个小时之间,我非常卡住。 I appreciate any help!
我很感激任何帮助!
Nearly there, just a GROUP BY
and some aggregation functions:几乎在那里,只有一个
GROUP BY
和一些聚合函数:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.