[英]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.