我需要从2个不同的表,产品和订单中选择数据,订单表将productid作为外键
我需要一个显示产品表中某些列的查询,具体取决于订单表中的最大订单数
我尝试了以下查询
select sc_products.id, sc_products.name from sc_products, sc_orders where sc_orders.product = sc_products.id
此查询只返回数据,并复制产品表中的ID 如
Full Texts id name
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt
Edit Delete 10 Black-White Cats
Edit Delete 10 Black-White Cats
Edit Delete 4 Aquarius Rhinestone T Shirt
Edit Delete 4 Aquarius Rhinestone T Shirt
Edit Delete 249 Volleyball Mom Blue Rhinestone T Shirt
Edit Delete 249 Volleyball Mom Blue Rhinestone T Shirt
我的查询后显示上述结果,我只需要显示多次排序的记录,我需要count
我需要一个像
这样的结果 id name count
Edit Delete 9 3 Gold-Silver Elephants Rhinestone T Shirt 10
Edit Delete 10 product 2 15
答案 0 :(得分:0)
要完成此操作,您需要使用聚合函数COUNT。
我们提供GROUP BY以确保仅在唯一产品条目上进行计数。注意:scp.id足以满足此要求,但所有非聚合列必须包含在GROUP BY中。
最后,我们使用HAVING将结果限制为只有那些有多个订单的记录(即计数> 1)。
SELECT scp.id, scp.name, COUNT(sco.product)
FROM sc_products scp
INNER JOIN sc_orders sco ON scp.id = sco.product
GROUP BY scp.id, scp.name
HAVING COUNT(sco.product) > 1;
答案 1 :(得分:0)
试试这个:
SELECT p.id, p.name, COUNT(o.id) orderCnt
FROM sc_products p
INNER JOIN sc_orders o ON o.product = p.id
GROUP BY p.id HAVING COUNT(o.id) > 1
ORDER BY orderCnt DESC