2017-03-07 34 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'