[英]SQL query or sub-query?
我在MySQL中有一张学生信息表,看起来像这样(简化):
| age : int | city : text | name : text |
-----------------------------------------------------
| | | |
我希望选择给定城市中的所有学生姓名和年龄,以及每个学生的年龄组中还有多少其他学生(即,有多少学生分享他的年龄值)。
我设法通过子查询来完成; 就像是:
select
name,
age as a,
(select
count(age)
from
tbl_students
where
age == a)
from
tbl_students
where
city = 'ny'
但这似乎有点慢,而且我也不是SQL向导,所以我想问一下是否有更聪明的方法可以做到这一点。 该表是按年龄和城市索引的。
select
t1.name,
t1.age as a,
count(t2.age) NumberSameAge
from
tbl_students t1 inner join tbl_students t2
on t1.age=t2.age
where
city = 'ny'
group by t1.name, t1.age
未经测试,但类似的东西。 向加入时的groupby发出敬意。 有时这可能会更快,因为您正在运行的查询对返回的每一行都执行嵌套子查询,而我上面发布的查询(或至少是具有join和groupby的结构)仅对相关学生执行查询一旦。
捕获同时捕获所有内容的子查询(相对于运行1000次子查询的1000行)可能更容易。
SELECT Age, count(*) AS SameAge FROM tbl_students
进行完整查询:
SELECT t.Name, t.Age, s.SameAge
FROM tbl_students t
INNER JOIN (
SELECT Age, count(*) AS SameAge FROM tbl_students
) AS s
ON (t.Age = s.Age) -- m:1
WHERE t.City = 'NY'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.