2017-03-07 116 views
1

下面是一個例子,所以我有表user和表city,他們是這樣的:如何加速從兩個表中搜索的sql查詢?

user列(USER_ID,city_id,時間戳)[USER_ID和city_id是獨一無二]

city列是(CITY_NAME,city_id)[city_id是獨一無二]

我想獲得用戶數量從某城市一個給定的日期,所以基本上我做了這樣的:

select city_id, city_name, 
    (select count(user.user_id) 
    from user, city 
    where DATE_FORMAT(user.timestamp, '%Y-%m-%d') = '2017-03-07' 
    and user.city_id = ct.city_id) as user_count 
from city ct 
where (city_id = 20 or city_id = 30) 

和Result:

city_id, city_name, user_count 
20  New York 100 
30  LA   200 

然後,我意識到這是不是直接用於

select count(user.user_id) 
from user, city 
where DATE_FORMAT(user.timestamp, '%Y-%m-%d') = '2017-03-07' 
    and user.city_id = 20 

這是爲什麼搜索方式慢?原始搜索中是不是ct.city_id已被設置爲20或30?我應該如何優化搜索並以我想要的表格格式獲得結果?

+0

你有這些表的索引嗎? –

+2

您的第二個查詢*與第一個查詢不相同。第二個查詢正在執行'CROSS JOIN',第一個查詢正在執行'INNER JOIN'。這種類型的隱式'JOIN'語法也已被棄用[*超過25年*](http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt)。你應該使用明確的'JOIN's。如果需要,它們更清晰,更清晰,並且更容易轉換爲「外部連接」。 – Siyual

回答

6

你可以提高你的查詢,避免子查詢和使用內部連接和group by

select city_id, city_name, count(user.user_id) 
from user 
inner join city on user.city_id = city.city_id 
where DATE_FORMAT(user.timestamp, '%Y-%m-%d') = '2017-03-07' 
and city_id in (city_id = 20 or city_id = 30) 
group by city_id, city_name 
+1

@RaymondNijland ..非常感謝ON條款 – scaisEdge

0

試試這個:

select city_id, city_name, count(user.user_id) as user_count 
from city ct 
inner join user on user.city_id = ct.city_id 
where (ct.city_id = 20 or ct.city_id = 30) 
AND DATE_FORMAT(user.timestamp, '%Y-%m-%d') = '2017-03-07'