查询1:
SELECT a.name,a.id
FROM name_list AS a
WHERE a.created_time BETWEEN "2013-03-14 00:00:00" AND "2013-03-14 23:59:59"
查询2:
SELECT address_nr
FROM address_list
WHERE user_id="1117770"
LIMIT 1
要执行查询1和2,我只需要0.003秒。但是当我将它们组合起来并将第二个查询作为子查询时,如下所示:
SELECT a.name,a.id,(SELECT address_nr FROM address_list WHERE user_id=a.id LIMIT 1) as 'address'
FROM name_list AS a
WHERE a.created_time BETWEEN "2013-03-14 00:00:00" AND "2013-03-14 23:59:59"
我需要1秒才能执行它。当我检索数千个数据时,它需要数千秒。
有人可以指导我吗?谢谢!
答案 0 :(得分:2)
尝试连接,而不是使用子查询。这应该明显更快:
SELECT a.name,a.id,b.address_nr address
FROM name_list a
LEFT JOIN address_list b ON a.id=b.user_id
WHERE a.created_time BETWEEN "2013-03-14 00:00:00" AND "2013-03-14 23:59:59"
您的子查询花费这么长时间的原因是因为它不只是运行两个查询,而是在主查询的结果集中为每一行运行一个主查询和子查询。如果表a有1000行,则表示您正在运行1001个查询。