首页 > 试题广场 >

Mysql中表student_table(id,name,b

[单选题]
Mysql中表student_table(id,name,birth,sex),查询男生、女生人数分别最多的3个姓氏及人数,正确的SQL是()?
  • SELECT   sex ,substr(name,1,1) as first_name ,count(*) as c1 
    from student_table where length(name) >=1
    group by first_name , sex order by sex ,c1 desc limit 3 ;
  • SELECT   sex ,substr(name,1,1) as first_name ,count(*) as c1 
    from student_table where length(name) >=1 and sex = '男'
    group by first_name order by sex ,c1 desc limit 3
    union all
    SELECT sex ,substr(name,1,1) as first_name ,count(*) as c1
    from student_table where length(name) >=1 and sex = '女'
    group by first_name order by sex ,c1 desc limit 3 ;
  • select * from (
    SELECT sex ,substr(name,1,1) as first_name ,count(*) as c1
    from student_table where length(name) >=1 and sex = '男'
    group by first_name order by sex ,c1 desc limit 3
    ) t1
    UNION all
    select * from (
    SELECT sex ,substr(name,1,1) as first_name ,count(*) as c1
    from student_table where length(name) >=1 and sex = '女'
    group by first_name order by sex ,c1 desc limit 3
    ) t2 ;
  • select * from (
    SELECT sex ,substr(name,1,1) as first_name ,count(*) as c1
    from student_table where length(name) >=1 and sex = '男'
    group by first_name having c1 >=3 order by sex ,c1 desc
    ) t1
    UNION all
    select * from (
    SELECT sex ,substr(name,1,1) as first_name ,count(*) as c1
    from student_table where length(name) >=1 and sex = '女'
    group by first_name having c1 >=3 order by sex ,c1 desc limit 3
    ) t2 ;
这题非常难顶,关于B和C
B是直接报错的语句
原因是在于union和order by的优先级问题
虽然没有明说,但是目前看来union是高于order by和limit的
在Mysql的参考手册中,并没有对union和order by的优先级进行说明,它建议的方法是,对SQL语句加上(),这样能使SQL的语义更清晰.
发表于 2022-03-10 18:47:28 回复(2)
在用union组合查询时,只能使用一条order by子句,它必须位于最后一条select语句之后。对于结果集,不存在用一种方式排序一部分,而用另一种方式排序另一部分的情况,因此不允许使用多条order by子句。
发表于 2022-03-20 10:42:37 回复(1)
为什么此处的 sex 不在分组中,却依然可以被select
发表于 2022-04-29 22:47:19 回复(8)
根本就没有正确答案,group by 怎么能直接用first_name,应该用
group by substr(name,1,1)
发表于 2022-03-15 09:18:29 回复(3)
为什么要对sex进行order by?
发表于 2022-10-25 12:31:47 回复(1)
为什么加length(name) >=1这条语句呢,有人能告诉我一下吗😄

发表于 2022-02-23 14:20:31 回复(1)
为什么B选项不对呢,B是C的简写啊
发表于 2021-12-21 14:19:32 回复(14)
UNION ALL 所连接的索引结果必须起别名
发表于 2022-07-17 08:22:40 回复(2)
请问一下,group by 不是在select之前执行吗,为什么在group by中能提前用first_name呢?
编辑于 2022-07-19 18:54:36 回复(1)
B选项确实会出错,原因是`UNION ALL`语法出错,如果想在`UNION`语句中使用`ORDER BY`,则UNION子句需要添加小括号。

发表于 2024-05-09 18:00:48 回复(0)
想问问order by 后面sex有必要吗?
编辑于 2024-02-18 18:03:22 回复(0)
答案没有一个是对的
发表于 2023-03-17 22:16:31 回复(0)
D为啥错了,闹不明白了
发表于 2023-01-12 16:32:04 回复(1)
如果需要对union或者union all组合查询结果进行过滤的时候,查询语句要放在最后,如果被合并的查询需要预先过滤,那么可以使用子查询的方式将过滤的条件分别加入。
发表于 2022-12-01 10:08:04 回复(0)
C选项 sex没有group by怎么就出现在select后面了?
发表于 2022-09-26 22:57:28 回复(1)
这上面自身题目的正确率是好多哟  有点持怀疑态度
发表于 2022-07-18 10:44:58 回复(0)
group by 是先执行的,怎么能用select中起的别名first_name呢?这不全错了吗


发表于 2022-04-18 20:30:10 回复(2)
怎么我的答题卡上只能看到AB选项,做完题后看解析C选项才出来了
发表于 2022-02-21 23:14:17 回复(0)