2013-04-12 96 views
0

是否有任何其他方式來編寫此查詢? 我試圖在子查詢中做它,但它不工作,因爲有多個列。看起來這個查詢只能自行工作。請指正最常見的值子查詢MySql

記錄

PK的recordId

dateViewed

CarViewed

我想這

SELECT R.`dateViewed` FROM Records ,(
    SELECT R.CarViewed, COUNT(R.CarViewed) as cnt FROM Records R 
    GROUP BY R.CarViewed 
    ORDER BY cnt DESC 
    LIMIT 1) AS favouriteCarOfTheDay 
    GROUP BY R.`dateViewed 

然後我嘗試這個

SELECT R.`dateViewed` ,COUNT(R.CarViewed) as cnt FROM Records , 
    (
    SELECT R.CarViewed FROM Records R 
    GROUP BY R.CarViewed 
    ORDER BY cnt DESC 
    LIMIT 1) AS favouriteCarOfTheDay 
    GROUP BY R.`dateViewed 

沿着我嘗試過的許多其他查詢,我不知道如何讓它工作。

簡而言之,我希望獲得最常見的汽車。

像: dateViewed favouriteCarOfTheDay

2012-09-22 | Nissan 

2012-09-23 | BMW 

回答

0

試試這個

SELECT R.`dateViewed` ,COUNT(R.CarViewed) as cnt ,R.CarViewed FROM Records R 
    GROUP BY R.`dateViewed 
    ORDER BY COUNT(R.CarViewed) DESC 
+0

至於我可以看到,將在總回報的一個記錄。我認爲他希望每天都有記錄。 –

+0

它按照查看日期分組,所以沒有一個記錄 –

+0

但是,最終的LIMIT 1是不是意味着它只返回一條記錄? –

0

我認爲以下應工作(聲明,不是所有的我自己的作品,改編自一個答案在another question

SELECT DISTINCT 
    R.dateViewed, 
    R.CarViewed 
FROM Records R 
WHERE 
    R.dateViewed = 
     (SELECT R2.dateViewed FROM 
      (
       SELECT R1.dateViewed, COUNT(*) AS numViewed 
       FROM Records R1 
       WHERE R1.CarViewed = R.CarViewed 
       GROUP BY R1.dateViewed 
       ORDER BY R1.numViewed DESC 
      ) AS R2 
      LIMIT 1 
     ) 
ORDER BY r.dateViewed 
0

這樣的事情真的很糟糕這樣做在MySQL所以它實際上可能比慢兩個相關子查詢,但至少它同時返回轎車,的觀看次數:

SELECT counts.`dateViewed`,counts.`CarViewed` as favourite_car, counts.cnt 
FROM 
(SELECT R.`dateViewed` ,R.`CarViewed`, COUNT(*) as cnt 
FROM Records 
GROUP BY R.`dateViewed` ,R.`CarViewed` 
) as counts JOIN 
(SELECT R.`dateViewed`, MAX(cnt) as cnt 
FROM 
(SELECT R.`dateViewed` ,R.`CarViewed`, COUNT(*) as cnt 
FROM Records 
GROUP BY R.`dateViewed` ,R.`CarViewed` 
) as q 
GROUP BY R.`dateViewed`) as maxes 
ON counts.cnt=maxes.cnt