位置
|
Select區間
|
From區間
|
Where區間
|
意義
|
一個子查詢回傳資料給母查詢當作一個欄位使用,只能回傳一筆單欄資料,此時的where條件能與母查詢的from區塊比對。
|
當作一個templatetable,可以給select、where直接使用,也可以與join系列聯合使用。
|
當作一種條件比對資料,透過in、exist、=等運算子來做條件限制
|
#假如這是記錄使用者的訂單
drop table user_order_A;
CREATE TABLE user_order_A (
id bigint(20) NOT NULL AUTO_INCREMENT COMMENT '訂單ID',
name varchar(20) NOT NULL COMMENT '誰的訂單',
PRIMARY KEY(id)
)AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
#假如有A、B、C三位使用者下單
insert into user_order_A(id,name) values (1, 'A');
insert into user_order_A(id,name) values (2, 'B');
insert into user_order_A(id,name) values (3, 'C');
insert into user_order_A(id,name) values (4, 'A');
insert into user_order_A(id,name) values (5, 'B');
insert into user_order_A(id,name) values (6, 'C');
#假如這是記錄每訂單的項目價錢
drop table products_table;
CREATE TABLE products_table (
order_id bigint(20) NOT NULL COMMENT '關連訂單id',
product_name varchar(255) NOT NULL,
price bigint(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into products_table(order_id,product_name,price) values (1, "商品1", 20);
insert into products_table(order_id,product_name,price) values (3, "商品2", 10);
insert into products_table(order_id,product_name,price) values (2, "商品3", 50);
insert into products_table(order_id,product_name,price) values (5, "商品4", 10);
insert into products_table(order_id,product_name,price) values (5, "商品5", 10);
insert into products_table(order_id,product_name,price) values (6, "商品6", 80);
insert into products_table(order_id,product_name,price) values (1, "商品7", 10);
insert into products_table(order_id,product_name,price) values (2, "商品8", 10);
insert into products_table(order_id,product_name,price) values (3, "商品9", 40);
insert into products_table(order_id,product_name,price) values (2, "商品2", 10);
insert into products_table(order_id,product_name,price) values (4, "商品1", 20);
#使用子查詢select底下
SELECT user_order_A.id,
user_order_A.name,
(SELECT
SUM(products_table.price)
FROM
products_table
WHERE user_order_A.id = products_table.order_id
) AS price
FROM
user_order_A ;
結果:
使用在FROM後的JOIN子查詢
SELECT
user_order_A.id,
user_order_A.name,
products_table.price
FROM user_order_A
JOIN (SELECT
SUM(products_table.price),
products_table.order_id ,
products_table.price
FROM products_table
GROUP BY products_table.order_id
)AS products_table
ON(user_order_A.id= products_table.order_id)
GROUP BY user_order_A.id;
結果:
使用在WHERE後的子查詢條件資料
SELECT user_order_A.id,
user_order_A.name,
(SELECT
SUM(products_table.price)
FROM
products_table
WHERE user_order_A.id = products_table.order_id
) AS price
FROM
user_order_A
WHERE
user_order_A.name IN (SELECT name FROM user WHERE user.id > 0)結果︰
其它文章
沒有留言:
張貼留言