mysql查询异常行为

时间:2016-02-02 16:07:02

标签: mysql sql

我在mysql中有三个表:

1:主题

code    title                    L-T-P   credits
CE10001 APPLIED MECHANICS        3-1-0  4
CH10001 CHEMISTRY I              3-1-0  4
CS20006 SOFTWARE ENGINEERING     3-0-0  3
CS21002 SWITCHING CIRCUITS AND LOGIC D  3-1-0   4
CS21003 ALGORITHMS - I  3-1-0   4
CS21004 FORMAL LANGUAGE AND AUTOMATA T  3-1-0   4
CS29002 SWITCHING CIRCUITS LABORATORY   0-0-3   2
CS29003 ALGORITHMS LABORATORY   0-0-3   2

2:研究

rollno      code
15CS10001   CH10001
15CS10002   CH10001
15CS10003   CH10001
15CS10004   CH10001
15CS10005   CH10001
15CS10006   CH10001
15CS10007   CH10001
15CS10008   CH10001
15CS10009   CH10001
15CS10010   CH10001
15CS10011   CH10001
15CS10012   CH10001

3:学生

rollno      name
12CS10001   A GOPI
12CS10002   AAYUSH SINGHAL
12CS10003   ABHISHEK KUMAR
12CS10004   AKSHAY GUPTA
12CS10005   AMRIT PATEL
12CS10006   ANKIT KUMAR GUPTA
12CS10007   ARKANATH PATHAK
12CS10008   ASEEM PATNI
12CS10009   AVANTSA NAGA RAJITHA
12CS10010   AYUSH VERMA
12CS10011   B SRUJAN

我想选择所有学生来自单一批次的科目。批量是rollno的前6个字母(例如。12CS60R13来自批次12CS60

我写了以下查询:

select st.rollno,sub.title 
from studies as st , subject as sub
where sub.code = st.code
group by st.code,(substring(st.rollno,1,6)) 
having count(rollno) = 
(select count(stu1.rollno) from student as stu1
    where substring(stu1.rollno,1,6) = substring(st.rollno,1,6));

我得到以下结果,这是正确的。

rollno      title
15CS10001   CHEMISTRY I
14CS10001   SOFTWARE ENGINEERING
14CS10001   SWITCHING CIRCUITS AND LOGIC D
13CS10001   OPERATING SYSTEMS
13CS10001   COMPUTER NETWORKS
12CS10001   DATABASE MANAGEMENT SYSTEMS
12CS10001   COMPUTER GRAPHICS
15CS60D01   DESIGN LABORATORY
15CS60D01   DISTRIBUTED SYSTEMS
15CS10001   ELECTRICAL ENGINEERING I
15CS10001   ENGINEERING MATHEMATICS I
15CS10001   ENGINEERING DRAWING I
15CS10001   WORKSHOP PRACTICE I
15CS10001   PHYSICS I

但是当我从select中删除st.rollno时,我收到了以下错误。

<code>enter image description here</code> 即使我没有更改select语句以外的任何内容,为什么我会收到错误?

2 个答案:

答案 0 :(得分:2)

SQL标准要求HAVING必须仅引用GROUP BY子句中的列或聚合函数中使用的列。但是,MySQL支持对此行为的扩展,并允许HAVING引用SELECT列表中的列和外部子查询中的列。

http://dev.mysql.com/doc/refman/5.5/en/select.html

答案 1 :(得分:1)

试试这个:

Select title from (
  select st.rollno,sub.title 
from studies as st , subject as sub
where sub.code = st.code
group by st.code,(substring(st.rollno,1,6)) 
having count(rollno) = 
(select count(stu1.rollno) from student as stu1
    where substring(stu1.rollno,1,6) = substring(st.rollno,1,6)))A;