您必须在 *p_id* 字段上的products和orderitemINNER JOIN
表之间使用,因为这是绑定两个表的公共字段。将仅获取两个表之间的匹配记录。连接将匹配所有匹配的记录,因为 ordereditem 值已经按 *p_id* 列分组,您将看到 products 表中的所有唯一产品信息以及基于 COUNT(p_id) 信息输出的订单计数。INNER JOIN
单击此处查看 SQL Fiddle 上的演示。
脚本:
CREATE TABLE products
(
p_id INT NOT NULL
, p_name VARCHAR(20) NOT NULL
, p_image_path VARCHAR(255) NOT NULL
);
CREATE TABLE orderitem
(
orderid INT NOT NULL
, p_id INT NOT NULL
);
INSERT INTO products (p_id, p_name, p_image_path) VALUES
(1, 'product 1', '~\image 1'),
(2, 'product 2', '~\image 2'),
(3, 'product 3', '~\image 3');
INSERT INTO orderitem (orderid, p_id) VALUES
(1, 2),
(1, 1),
(1, 3),
(1, 2),
(1, 2),
(1, 1);
SELECT p.p_id
, p.p_name
, p.p_image_path
, COUNT(o.p_id) AS orderedcount
FROM products p
INNER JOIN orderitem o
ON p.p_id = o.p_id
GROUP BY p.p_id
ORDER BY orderedcount DESC;
输出:
P_ID P_NAME P_IMAGE_PATH ORDEREDCOUNT
---- ---------- ------------ ------------
2 product 2 ~image 2 3
1 product 1 ~image 1 2
3 product 3 ~image 3 1