我有3个实体:
一条街 有很多房子 哪个有很多Windows
在MySql中,它看起来像这样:
Street House Window
------------- ------------------------- ------------------------
| id | name | | id | street_id | name | | id | house_id | type |
------------- ------------------------- ------------------------
| 1 | SA | | 1 | 1 | HA | | 1 | 1 | WA |
------------- ------------------------- ------------------------
| 2 | SB | | 2 | 3 | HB | | 2 | 1 | WB |
------------- ------------------------- ------------------------
| 3 | SC | | 3 | 1 | HC | | 3 | 1 | WC |
------------- ------------------------- ------------------------
我需要能够用简单的英语写一些查询:
我无法弄清楚如何做到这一点,问题是Windows是由Streets通过Houses拥有的。
我尝试过这样的事情:
SELECT street.*, COUNT(*) AS window_count FROM street
LEFT JOIN house ON street.id = house.street_id
LEFT JOIN window ON house.id = window.house_id
GROUP BY street.id
这似乎产生了我想要的结果,但这非常慢(超过2分钟)。我需要LEFT连接,因为我想返回所有Streets,即使它们没有Houses或Windows。
有关最佳方法的任何想法吗?我遇到的困难使我怀疑我的数据库结构,也许我需要以不同的方式存储这些数据?
答案 0 :(得分:0)
此代码可以更快地运行,因为它在交叉
之前被分组SELECT
street.*,
CASE WHEN wc IS NULL THEN 0 ELSE wc END AS window_count
FROM street
LEFT JOIN (
SELECT street.id, SUM(WH) AS wc
FROM house
LEFT JOIN (
SELECT house.id, COUNT(*) AS WH
FROM window
GROUP BY house.id
) AS W
ON house.id = W.house_id
GROUP BY street.id
) AS H
ON street.id = H.street_id