Mysql数据联接用法

1、自联结
mysql> select p1.prod_id,p1.prod_name

from products as p1,products as p2
where p1.vend_id=p2.vend_id and p2.prod_id='DTNTR';
或者
mysql> select prod_id
from products
where vend_id = (select vend_id
from products
where prod_id = 'DTNTR');
2、自然联结
mysql> select c.*,o.order_num,o.order_date,oi.prod_id,oi.quantity,oi.item_price
from customers as c,orders as o,orderitems as oi
where c.cust_id = o.cust_id and oi.order_num=o.order_num and prod_id= 'FB';
或者
mysql> select *,order_num,order_date,prod_id,quantity,item_price
from customers INNER JOIN orders INNER JOIN orderitems
on customers.cust_id=orders.cust_id
and orderitems.order_num=orders.order_num
and prod_id='FB';
3、外部联结
mysql> select customers.cust_id,orders.order_num
from customers LEFT OUTER JOIN orders
oncustomers.cust_id=orders.cust_id; #列出customers中所有的cust_id,包括无关联的
+---------+-----------+
| cust_id | order_num |
+---------+-----------+
|  10001| 20005 |
|  10002| NULL |
|  10003| 20006 |
|  10004| 20007 |
|  10005| NULL |
|  10006| NULL |
|  10007| NULL |
|  10008| NULL |
+---------+-----------+
mysql> select customers.cust_id,orders.order_num
from customers RIGHT OUTER JOIN orders
oncustomers.cust_id=orders.cust_id; #列出orders中所有的cust_id,包括无关联的
+---------+-----------+
| cust_id | order_num |
+---------+-----------+
|  10001| 20005 |
|  10003| 20006 |
|  10004| 20007 |
+---------+-----------+
4、使用带聚集函数的联结
mysql> select customers.cust_name,customers.cust_id,count(orders.order_num) as num_ord
-> from customers INNER JOIN orders #此处可以使用LEFT/RIGHT OUTERJOIN
-> on customers.cust_id = orders.cust_id
-> group by customers.cust_id;


你可能感兴趣的:(mysql,Products,customers,quantity)