随笔 - 21  文章 - 0  评论 - 0  阅读 - 6155

mysql使用子查询

定义三个表:

①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; 

 

posted on   博览天下with天涯海角  阅读(72)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示