max()和count()sql

时间:2015-06-17 10:59:10

标签: mysql sql subquery

我有这些表格:

Customers ( cid , cname ) 
Products ( pid , pcolor)
Reservations ( pid , cid , date)

我需要知道最常被保留的产品是什么颜色,到目前为止我写了这个:

      SELECT p.color, count(p.pid) as j
      FROM products as p , reservations as res
      WHERE p.pid = res.pid
      GROUP BY p.color
      ORDER BY j DESC
      LIMIT 1

现在这个查询效果很好,但是有一点小问题,如果有2种不同颜色的产品保留了相同的次数,它只给出了其中一种(因为&#34 ;限制1")..我该怎么办?

1 个答案:

答案 0 :(得分:-1)

SELECT pr.pcolor, count(pr.pid)
FROM Products pr
JOIN Reservations res
ON pr.pid = res.pid
GROUP BY pr.pcolor