MySQL嵌套计数语句

时间:2013-07-29 21:26:04

标签: mysql

想象我有2张桌子,我想计算最畅销的艺术家:

  • 音乐(id,title,条形码)
  • 艺术家(条形码,艺术家)

    SELECT COUNT(m.barcode) AS sells, m.barcode, artist
    FROM music m
    LEFT JOIN artists a
    ON m.barcode = a.barcode
    GROUP BY m.barcode ORDER BY sells DESC
    

此查询返回例如:

  sells    | barcode |   artist
 ---------------------------------
   1000        123       jdoe
    500        223       kloe
    100        321       jdoe

如何计算jdoe复杂地销售了1100首音乐?

提前感谢任何提示

2 个答案:

答案 0 :(得分:1)

您应该将group bybarcode更改为artist(并从barcode声明中删除select

SELECT COUNT(m.barcode) AS sells, artist
FROM music m LEFT JOIN
     artists a
     ON m.barcode = a.barcode
GROUP BY artist
ORDER BY sells DESC;

答案 1 :(得分:0)

SELECT COUNT(m.barcode) AS popular, m.barcode, a.artist, SUM(a.sell) 
FROM `music` AS m 
LEFT JOIN `artists` AS a 
ON (m.barcode = a.barcode)
WHERE a.artist = 'jdoe'
GROUP BY m.barcode 
ORDER BY `popular` DESC