-- 添加數據以及如何查詢
CREATE DATABASE table;
CREATE TABLE t_shop(
_id INT PRIMARY KEY AUTO_INCREMENT,
_shopcode VARCHAR(30),
_name VARCHAR(40),
_fk INT
);
INSERT INTO t_shop(_shopcode,_name,_fk) VALUES
('n11','蘋果',1),
('n12','白菜',2),
('a13','冬瓜',3),
('n14','西瓜',4),
('n15','絲瓜',5),
('c16','苦瓜',6),
('m17','南瓜',5),
CREATE TABLE t_price(
_pid INT PRIMARY KEY,
_price FLOAT
);
INSERT INTO t_price(_pid,_price) VALUES
(1,9.0),
(2,3.2),
(3,5.5),
(4,6.0),
(5,6.3),
(6,6.6);
兩張表經過 t_shop._fk 和 t_price._pid 進行關聯
-- 要求
-- 1 查詢全部瓜的全部信息,包括價格
SELECT * FROM t_price,t_shop WHERE t_shop._fk=t_price._pid AND t_shop._name LIKE '%瓜%'
-- 2 查詢價格在4.0 到8.0 的全部商品信息
SELECT * FROM t_price,t_shop WHERE t_shop._fk=t_price._pid AND t_price._price BETWEEN 4 AND 8
-- 3 查詢查詢同價格的商品信息
SELECT * FROM t_price,t_shop WHERE t_shop._fk=t_price._pid AND t_price._price INLECT t_price._price FROM t_price,t_shop WHERE t_shop._fk=t_price._pid GROUP BY t_price._price HAVING COUNT(*)>=2)
-- 4 查詢最高價格商品信息
SELECT * FROM t_price,t_shop WHERE t_shop._fk=t_price._pid AND t_price._price=(SELECT t_price._price FROM t_price,t_shop WHERE t_shop._fk=t_price._pid GROUP BY t_price._price ORDER BY t_price._price DESC LIMIT 1)
-- 5 查詢查詢商品價格最高的前三個商品的信息
SELECT * FROM t_price,t_shop WHERE t_shop._fk=t_price._pid GROUP BY t_price._price DESC LIMIT 3
-- 6 查詢全部商品的平均價格
SELECT AVG(t_price._price) FROM t_price,t_shop WHERE t_shop._fk=t_price._pid
-- 7 查詢全部瓜的平均價格
SELECT AVG(t_price._price) FROM t_price,t_shop WHERE t_shop._fk=t_price._pid AND t_shop._name LIKE '%瓜%'
-- 8 查詢最高商品的價格是最低商品的價格的倍數是多少
SELECT(SELECT MAX(t_price._price) FROM t_price,t_shop WHERE t_shop._fk=t_price._pid)/(SELECT MIN(t_price._price) FROM t_price,t_shop WHERE t_shop.=t_price._pid)
-- 9 查詢和絲瓜有相同價格的商品信息
SELECT * FROM t_price,t_shop WHERE t_shop._fk=t_price._pid AND t_price._price=(SELECT t_price._price FROM t_price,t_shop WHERE t_shop._fk=t_price._pid AND t_shop._name="絲瓜") AND t_shop._name!="絲瓜"
-- 10 查詢 是最低價格的商品的整數倍價格,的商品信息(例如最低價格商品是白菜,3.0。
-- 它的整數倍3.0 6.0 9.0 等等這些價格的商品信息)。
SELECT t_price._price FROM t_price,t_shop WHERE t_shop._fk=t_price._pid AND t_price._price%(SELECT t_price._price FROM t_price,t_shop WHERE t_shop._fk=t_price._pid AND t_price._price<=ALL(SELECT t_price._price FROM t_price,t_shop WHERE t_shop._fk=t_price._pid))=0
code