定义三个表:
①order表,包含订单号order_num和客户id(cust_id),此表表示客户的购物记录。
CREATE TABLE `order` ( order_num INT, cust_id INT ); SELECT * FROM `order`;
②orderitems表,包含订单号order_num和订单内容content。
CREATE TABLE orderitems ( order_num INT, content VARCHAR(255) )
③customers表,包含客户id(cust_id),客户名字(cust_name)和客户联系方式cust_contact。
CREATE TABLE customers ( cust_id INT, cust_name VARCHAR(10), cust_contact VARCHAR(10) );
插入数据:
INSERT INTO customers VALUES(2232249, '大力士', ''), (2232248, '大帝石', '');
INSERT INTO `order` VALUES(1001, 2232249), (1002, 2232248);
INSERT INTO orderitems VALUES(1001, '水果 纸巾'), (1002, '水果 衣服');
检索所有购买水果的客户信息:可以先检索orderitems得出对应的订单号order_num,然后在使用检索出的order_num来检索出对应的cust_id,之后利用检索出的cust_id从customers得到客户信息。
SELECT cust_id, cust_name FROM customers WHERE cust_id IN (SELECT cust_id FROM `order` WHERE order_num IN (SELECT order_num FROM orderitems WHERE INSTR(content, '衣服') != 0) )
显示每个客户的订单总数:从customers表中检索每个客户,对于每个客户再使用count(*)统计order表中的数量。
SELECT cust_id, cust_name, (SELECT COUNT(*) FROM `order` WHERE `order`.`cust_id` = customers.`cust_id`) AS `count` FROM customers;
标签:customers,cust,mysql,id,num,使用,查询,order,SELECT From: https://www.cnblogs.com/dadishi/p/17066018.html