Mysql:哪个披萨更喜欢客户端

时间:2013-03-01 09:21:38

标签: mysql database

我有这个数据的表格:

 1. John | seafood pizza 
 2. Mike | pepperoni pizza 
 3. Mike | pepperoni pizza
 4. John | original pizza 
 5. Mike | original pizza 
 6. John | seafood pizza
 7. John | pepperoni pizza

...

如何编写一个给我结果的查询:

John | seafood pizza
Mike | pepperoni pizza

如果客户的许多比萨饼的数量相同,结果可能是比萨饼的名称。

3 个答案:

答案 0 :(得分:2)

让我们一步一步地采取行动

以下查询将为您提供每个客户订购各种披萨的次数

SELECT name, pizza, COUNT(*) AS cnt 
FROM yourTable 
GROUP BY name, pizza

那么我们如何从中获得最常订购的披萨呢?我们必须首先知道,每个客户订购的比萨饼数量是多少

SELECT name, MAX(cnt) AS cnt FROM (
  SELECT name, pizza, COUNT(*) AS cnt 
  FROM yourTable 
  GROUP BY name, pizza
) AS subquery GROUP BY name

然后使用此号码选择实际比萨饼名称

SELECT name, pizza, COUNT(*) AS cnt 
FROM yourTable AS t
CROSS JOIN (
  SELECT name, MAX(cnt) AS cnt FROM (
    SELECT name, pizza, COUNT(*) AS cnt 
    FROM yourTable 
    GROUP BY name, pizza
  ) AS subquery GROUP BY name
) AS sq
USING(name,cnt)
GROUP BY name, pizza

答案 1 :(得分:0)

我会按用户和披萨对计数进行分组,然后将其用作查询的数据源,该查询找到groupwise最大值(使用max concat技巧)。这并不难:

SELECT user, SUBSTRING(MAX(CONCAT(LPAD(freq, 6, '0'),pizza)),7)
FROM
(SELECT user, pizza, COUNT(*) AS freq
FROM user_likes
GROUP BY user, pizza) ilv
GROUP BY user

答案 2 :(得分:-1)

让我们有一个简单的解决方案: 首先,我们有两个栏目,名称和食物。 您可以轻松列出喜爱的顾客的食物:

CREATE TEMPORARY TABLE tbltemp AS (
SELECT name, food, COUNT( * ) c
FROM food
GROUP BY name, food
);

现在我们有所有的食物。 然后你可以通过递减计数来订购它:

SELECT *
FROM tbltemp
ORDER BY c DESC

现在您有一个描述客户最喜欢的列表。

更新:

取代第二个查询,将其替换为:

SELECT tbl1 . *
FROM (

SELECT name, food, COUNT( * ) c
FROM food
GROUP BY name, food
) AS tbl1, (

SELECT name, food, COUNT( * ) c
FROM food
GROUP BY name, food
) AS tbl2
WHERE tbl1.c = tbl2.c
AND tbl2.name = tbl1.name
AND tbl2.food = tbl1.food
AND tbl1.c = (
SELECT c
FROM tbltemp
ORDER BY c DESC
LIMIT 1 )

此查询结果是您的问题目标。