如何从两个表中获取记录以及计数?

时间:2012-04-29 13:43:09

标签: mysql sql

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

我有以下内容返回最多买的商品,但我无法弄清楚如何从{{1}返回每个商品的p_name p_pricep_image_path(p_id)表}

products

我希望这是有道理的

6 个答案:

答案 0 :(得分: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 

答案 1 :(得分:2)

您必须在* p_id *字段的产品 orderitem 表之间使用INNER JOIN,因为这是绑定这两个表的公共字段。 INNER JOIN将仅获取两个表之间的匹配记录。联接将匹配所有匹配的记录,因为ordereditem值已经按* p_id *列分组,您将看到产品表中的所有唯一产品信息以及基于COUNT(p_id)信息输出的订单计数。 / p>

Click here to view the demo at 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

答案 2 :(得分: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

答案 3 :(得分: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

答案 4 :(得分: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

答案 5 :(得分: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