nut*_*nut 1 mysql group-by subquery where
我正在学习mysql手册:http: //dev.mysql.com/doc/refman/5.6/en/example-maximum-column-group-row.html我和"where.s1.article =混淆了s2.article'部分,这是什么意思?
Task: For each article, find the dealer or dealers with the most expensive price.
+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
| 0001 | A | 3.45 |
| 0001 | B | 3.99 |
| 0002 | A | 10.99 |
| 0003 | B | 1.45 |
| 0003 | C | 1.69 |
| 0003 | D | 1.25 |
| 0004 | D | 19.95 |
+---------+--------+-------+
SELECT article, dealer, price
FROM shop s1
WHERE price=(SELECT MAX(s2.price)
FROM shop s2
WHERE s1.article = s2.article);
+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
| 0001 | B | 3.99 |
| 0002 | A | 10.99 |
| 0003 | C | 1.69 |
| 0004 | D | 19.95 |
+---------+--------+-------+
Run Code Online (Sandbox Code Playgroud)
我正在尝试编写类似的代码:
SELECT sex, name, birthday
From user
Where birthday=(SELECT MAX(birthday)
FROM user
group by sex);
Run Code Online (Sandbox Code Playgroud)
但我的输出错误:子查询返回超过1行,为什么?
原始查询称为相关子查询.WHERE子查询中的子句将找到的最大值限制为与外部查询正在处理的行匹配的文章.
在您的查询中,您没有WHERE子句,因此它处理表中的所有内容.然后返回按性别分组的结果.我假设你的桌子里有两个性别,所以它返回一行,其中男性的最大值,另一行包含女性的最大值.但是WHERE price = (<subquery>)要求子查询只返回一个结果,因为=只能与单个值一起使用.
您可以使用IN而不是=匹配多个返回值.这可能不是你想要的,但你还没有描述你想要查询的内容,所以很难说.
要获得每个性别中最年轻的人,您可以编写相关的子查询,如手册中的子查询:
select sex, name, birthday
from user u1
where birthday = (select max(birthday)
from user u2
where u1.sex = u2.sex)
Run Code Online (Sandbox Code Playgroud)
或者您可以使用带有分组子查询的联接:
select u1.sex, name, u1.birthday
from user u1
join (select sex, max(birthday) maxbirthday
from user
group by sex) u2
on u1.sex = u2.sex and birthday = maxbirthday
Run Code Online (Sandbox Code Playgroud)