1

我想从表中选择购买最多的商品orderitems,然后获取这些商品的详细信息并排序 DESC

我有以下返回最多购买的项目,但我不知道如何从表中返回每个项目(p_id)的p_name p_pricep_image_pathproducts

SELECT      p_id
        ,   COUNT( p_id ) AS p_id_count
FROM        orderitem
GROUP BY    p_id
ORDER BY    p_id_count $direction

我希望这是有道理的

4

6 回答 6

2
SELECT o.p_id, COUNT( o.p_id ) AS p_id_count, p.p_name, p.p_price, p.p_image_path
FROM orderitem o
INNER JOIN products p ON o.p_id = p.p_id
GROUP BY o.p_id
ORDER BY p_id_count 
于 2012-04-29T13:46:40.193 回答
2

您必须在 *p_id* 字段上的productsorderitemINNER 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
于 2012-04-29T13:53:21.993 回答
1

我假设产品的主键是 id 并且与 orderitem 的 p_id 有参考

SELECT o.p_id, COUNT( o.p_id ) AS p_id_count, p.p_name,p.p_price,p.p_image_path 
        FROM orderitem o
    INNER JOIN products p ON p.id = o.p_id 
        GROUP BY o.p_id
        ORDER BY o.p_id_count $direction
于 2012-04-29T13:51:34.010 回答
0
SELECT p_id, p_name, p_price, p_image_path, COUNT( p_id ) AS p_id_count
FROM orderitem
inner join products p on p.id = p_id
GROUP BY p_id
ORDER BY p_id_count $direction
于 2012-04-29T13:45:56.507 回答
0

您需要将 products 表与 orderitem 表连接起来。

SELECT p_id, p_name, p_price, COUNT( p_id ) AS p_id_count
    FROM orderitem
    LEFT JOIN products ON (orderitem.p_id = products.id)
    GROUP BY p_id, p_name, p_price
    ORDER BY p_id_count $direction
于 2012-04-29T13:46:26.807 回答
0
SELECT p_id, COUNT( p_id ) AS p_id_count
        FROM orderitem o, products p
        WHERE o.p_id = p.p_id
        GROUP BY p_id
        ORDER BY p_id_count $direction
于 2012-04-29T13:46:44.150 回答