Questions about subquery in mysql -
1、firstly, mysql version 5.5.40
2、following table data:
mysql> select * student; +----+-----------+ | id | name | +----+-----------+ | 1 | lily | | 2 | lucy | | 3 | nacy | | 4 | hanmeimei | +----+-----------+ 4 rows in set (0.00 sec) mysql> select * course; +------------+--------+ | student_id | course | +------------+--------+ | 1 | title | | 2 | title | | 3 | title | +------------+--------+ 3 rows in set (0.00 sec)
3、why sql return result set,what subquery return? when replace id name,i same result.how works?
mysql> select * student id in(select id course); +----+-----------+ | id | name | +----+-----------+ | 1 | lily | | 2 | lucy | | 3 | nacy | | 4 | hanmeimei | +----+-----------+ 4 rows in set (0.00 sec) mysql> select * student name in(select name course); +----+-----------+ | id | name | +----+-----------+ | 1 | lily | | 2 | lucy | | 3 | nacy | | 4 | hanmeimei | +----+-----------+ 4 rows in set (0.00 sec)
4、here code create tables , insert data:
create table `course` ( `student_id` int(11), `course` varchar(20) ) engine=myisam default charset=utf8; insert `course` values ('1', 'title'); insert `course` values ('2', 'title'); insert `course` values ('3', 'title'); create table `student` ( `id` int(11), `name` varchar(20) ) engine=myisam default charset=utf8; insert `student` values ('1', 'lily'); insert `student` values ('2', 'lucy'); insert `student` values ('3', 'nacy'); insert `student` values ('4', 'hanmeimei');
it called correlated subquery.
a correlated subquery subquery contains reference table appears in outer query.
you can read doc here : https://dev.mysql.com/doc/refman/5.5/en/correlated-subqueries.html
when have no id
field in course
table have table named id
in parent table student
parent field. no need give field allias when have identic field each other, join
.
but when have no id
field either parent table, return error
unknown column 'id' in 'field list'
Comments
Post a Comment