数据库子查询50
本文将从商品查询案例向大家介绍子查询
三个表:orders、orderitems、customers分别存储商品信息、订单信息、用户信息。当需要查询prod_id = 'TNT2’的商品订单用户的信息时。我们可能会如下查询:
select order_num from orderitems where prod_id = 'TNT2';
+-----------+
| order_num |
+-----------+
| 20005 |
| 20007 |
+-----------+
2 rows in set (0.00 sec)
select cust_id from orders where order_num in(20005,20007);
+---------+
| cust_id |
+---------+
| 10001 |
| 10004 |
+---------+
2 rows in set (0.00 sec)
select cust_name,cust_contact from customers where cust_id in(10001,10004);
+----------------+--------------+
| cust_name | cust_contact |
+----------------+--------------+
| Coyote Inc. | Y Lee |
| Yosemite Place | Y Sam |
+----------------+--------------+
2 rows in set (0.00 sec)
上述的查询方式我们称之为简单查询(即从单个数据库表中检索数据的单条语句),子查询如下:
select cust_name,cust_contact
from customers
where cust_id in(select cust_id
from orders
where order_num in (select order_num
from orderitems
where prod_id = 'TNT2'));
+----------------+--------------+
| cust_name | cust_contact |
+----------------+--------------+
| Coyote Inc. | Y Lee |
| Yosemite Place | Y Sam |
+----------------+--------------+
2 rows in set (0.00 sec)
上述的子查询是包含在where 从句中,也有字段中使用子查询的情况。
现在统计所有用户目前的订单数。
简单查询:
select cust_id from customers;
+---------+
| cust_id |
+---------+
| 10001 |
| 10002 |
| 10003 |
| 10004 |
| 10005 |
+---------+
5 rows in set (0.00 sec)
select count(*) from orders where cust_id = 10001;
+----------+
| count(*) |
+----------+
| 2 |
+----------+
1 row in set (0.01 sec)
select count(*) from orders where cust_id = 10002;
+----------+
| count(*) |
+----------+
| 0 |
+----------+
1 row in set (0.00 sec)
......依次查询
运用子查询:
select cust_id ,cust_name ,(select count(*)from orders where orders.cust_id = customers.cust_id ) orders from customers order by cust_name;
+---------+----------------+--------+
| cust_id | cust_name | orders |
+---------+----------------+--------+
| 10001 | Coyote Inc. | 2 |
| 10005 | E Fudd | 1 |
| 10002 | Mouse House | 0 |
| 10003 | Wascals | 1 |
| 10004 | Yosemite Place | 1 |
+---------+----------------+--------+
5 rows in set (0.00 sec)
从上可见,灵活运用子查询能极大的简化查询语句。