`
DavyJones2010
  • 浏览: 154965 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

MySQL: Where sub-query & From sub-query & Exists sub-query

阅读更多

1. A good comprehension model:

    1) Where expression: Fit this experssion into every row and get the true/false result.

#Where expression comprehension model
select * from stu where stu_name = 'zhangsan';

    2) Row: Regard as variable which enables basic math operation.

#Row comprehension model
#We can regard the second 'stu_name' as a variable whose value depends on the row cursor now pointing to
select stu_name from stu where stu_name = 'zhangsan'

     3) Result set: Regard as a temporary table which enables further query.

#We regard the sub-query result set as a temp table which enables further query
#We want to find the stu_name whose max score equals or larger than 80
select * from (select stu_name, max(stu_score) as stu_max from stu group by stu_name) as temp where stu_max >= 80;

 

2. Four Types of Sub-query

    1) Where sub-query

# Find the highest score and the corresponding stu_name, stu_course

# Solution 1: Where sub-query
# Regard the result of where sub-query as a value
select stu_name, stu_score, stu_course from stu where stu_score = (select max(stu_score) from stu);

# Solution 2: Order & Limit
select stu_name, stu_score, stu_course from stu group by stu_score limit 1;

 

#Find the highest score and the corresponding student in each course

#Using where sub-query
#But this kind of approach is not that precise.
#Just use the stu_score as the signal, there may be some other stu_score in other courses that equals the max(score).
select * from stu where stu_score in (select max(stu_score) from stu group by stu_course);
#There is an overlap in Literature course because the stu_score in Literature 50 equals the highest score that in Geograph 50
+----------+------------+-----------+
| stu_name | stu_course | stu_score |
+----------+------------+-----------+
| zhangsan | Math       |        90 |
| zhangsan | Literature |        50 |
| lisi     | Literature |        55 |
| zhaoliu  | Geograph   |        50 |
| zhaoliu  | Politic    |        99 |
+----------+------------+-----------+

 

     2) In sub-query

#The core thought lies behind From sub-query is regarding the result of inner query as a table based on which we can start a new outter query.

select * from (select max(stu_score) from stu group by stu_course) as temp;

 

#Find the avg score for students who has more than one invalid course.

#Using Where sub-query
#Most inner query find the stu_name who has more than one invalid course.
#Secondary inner query filter other useless columns for where sub-query
#Outter query find the average score for each students whose name lists in inner query.
select stu_name, avg(stu_score) from stu where stu_name in (select stu_name from (select stu_name, stu_score, sum(stu_score < 60) as invalid_count from stu group by stu_name having invalid_count >= 2) as temp) group by stu_name;
#Another way to find out the student name whose invalid course in more than one
select stu_name, count(*) as invalid_count from stu where stu_score < 60 group by stu_name having invalid_count >= 2;

 

    3) Exists sub-query

#Core thoughts lies on Exists sub-query is that 'Put the result of out query into inner query to judge the inner query true or false'

select * from category;

#First Level Category
####Secondary Category
#######Real Goods
#######Real Goods
####Secondary Category
#######Third Level Category
###########Real Goods
####Secondary Category

# All the categories are stored in category table,
# But some categories contains no goods but secondary category

# What if we want to figure out the category that directly contains goods?

select cat_id, cat_name from category where exists(select * from goods where goods.cat_id = category.cat_id);

 

分享到:
评论

相关推荐

    SQL21自学通

    - 子查询可以在SELECT、FROM或WHERE子句中嵌套使用。 - **在子查询中使用汇总函数:** - 可以在子查询中使用COUNT、SUM等函数。 - **子查询的嵌套:** - 子查询可以嵌套多层。 - **相关子查询:** - 相关子查询...

    MYSql常用命令.......................

    - `DELETE FROM table_name WHERE condition;` - **查询数据:** - `SELECT * FROM table_name;` #### 示例 - **创建一个名为 `school` 的数据库,并在其中创建一个名为 `teacher` 的表:** - `DROP DATABASE IF...

    kube-flannel.yml

    - operator: Exists effect: NoSchedule serviceAccountName: flannel initContainers: - name: install-cni image: jmgao1983/flannel:v0.11.0-amd64 command: - cp args: - -f - /etc/kube-flannel/...

    Mojo-mysql:Mojo-mysql 的只读发布历史

    $mysql-&gt;db-&gt;do('create table if not exists names (name text)');# Insert a few rowsmy $db = $mysql-&gt;db;$db-&gt;query('insert into names values (?)', 'Sara');$db-&gt;query('insert into names values (?)', '...

    sqlserver自学通

    - 示例:`SELECT FirstName, LastName FROM Employees WHERE Department = 'Sales';` - **总结:** SELECT语句的基本结构及其常见用途。 #### 三、表达式、条件语句与运算 - **表达式:** - 包括算术运算、字符...

    MYSQL常用指令

    - 删除数据:`DELETE FROM 表名 WHERE 条件;` **示例:** - 创建教师表: - `CREATE TABLE teacher (id INT(3) AUTO_INCREMENT NOT NULL PRIMARY KEY, name CHAR(10) NOT NULL, address VARCHAR(50) DEFAULT '北京...

    sql21自学通

    - `SELECT * FROM employees WHERE EXISTS (SELECT * FROM departments WHERE employees.department_id = departments.id AND departments.location = 'New York');` #### 八、操作数据 - **数据操作语句:** - ...

    SQL21自学通edit

    - 示例:`SELECT * FROM employees e1 WHERE NOT EXISTS (SELECT * FROM employees e2 WHERE e1.salary );` - **EXISTS、ANY、ALL的使用:** - EXISTS:检查子查询是否返回任何行。 - ANY:与子查询中的任意一行...

    MySQL开发教程.docx

    - `SELECT column_name(s) FROM table_name WHERE condition` 查询符合条件的数据。 - **高级功能:** - 排序与分页:`ORDER BY`, `LIMIT`。 - 子查询:`IN`, `EXISTS`。 - MySQL函数:聚合函数(`SUM`, `AVG`, ...

    MYSQL初学者使用指南

    - `DELETE FROM [表名] WHERE ...;` 从表中删除满足条件的记录。 - **查询数据:** - `SELECT * FROM [表名];` 查询表中的所有记录。 - **示例:** - 创建并使用名为`school`的数据库。 ```sql DROP ...

    MySQL常用命令

    - `CREATE TABLE table2 AS SELECT * FROM table1 WHERE 1&lt;&gt;1;` - **说明:** 这样做是为了避免复制数据,只复制表结构。 **复制表(包括数据):** - `CREATE TABLE table2 AS SELECT * FROM table1;` - **说明...

    SQL21自学通.pdf

    - 示例:`SELECT * FROM table1 WHERE id IN (SELECT id FROM table2 WHERE id IN (SELECT id FROM table3));` - **相关子查询:** - 相关子查询依赖于外层查询中的列值。 - 示例:`SELECT * FROM table1 WHERE ...

Global site tag (gtag.js) - Google Analytics