如何通过LEFT JOIN将MySQL用于COUNT?

时间:2012-01-11 16:34:45

标签: mysql count

如何使用MySQL来计算LEFT JOIN?

我有两张桌子,有时评级表没有照片评级所以我认为需要LEFT JOIN,但我也有COUNT声明..

照片

id  name        src
1   car         bmw.jpg
2   bike        baracuda.jpg

喜欢(picid是带有照片ID的外键)

id  picid   ratersip
4   1       81.0.0.0
6   1       84.0.0.0
7   2       81.0.0.0

此处用户只能使用其IP对一张图片进行评分。

我想按照最高评级的顺序组合这两个表。新表

联合

id  name    src            picid
1   car     bmw.jpg        1
2   bike    baracuda.jpg   2

(宝马获得最高评分)

我的MySQL代码:

SELECT * FROM photos 
LEFT JOIN ON photos.id=loves.picid 
ORDER BY COUNT (picid);

我的PHP代码:(更新和添加 - 工作示例......)

$sqlcount = "SELECT p . *
FROM `pics` p
LEFT JOIN (

SELECT `loves`.`picid`, count( 1 ) AS piccount
FROM `loves`
GROUP BY `loves`.`picid`
)l ON p.`id` = l.`picid`
ORDER BY coalesce( l.piccount, 0 ) DESC";

$pics = mysql_query($sqlcount);

4 个答案:

答案 0 :(得分:4)

MySQL允许您只按id列进行分组:

select
    p.*
from
    photos p 
    left join loves l on
        p.id = l.picid
group by
    p.id
order by
    count(l.picid)

话虽如此,我知道MySQL在group by非常糟糕,因此您可以尝试将loves计数放入联接中的子查询中以优化它:

select
    p.*
from
    photos p
    left join (select picid, count(1) as piccount from loves group by picid) l on
        p.id = l.picid
order by
    coalesce(l.piccount, 0)

我没有MySQL实例来测试哪个更快,所以测试它们。

答案 1 :(得分:2)

您需要使用子查询:

SELECT id, name, src FROM (
  SELECT photos.id, photos.name, photos.src, count(*) as the_count 
  FROM photos 
  LEFT JOIN ON photos.id=loves.picid 
  GROUP BY photos.id
) t 
ORDER BY the_count

答案 2 :(得分:1)

select
      p.ID,
      p.name,
      p.src,
      PreSum.LoveCount
   from
      Photos p
         left join ( select L.picid,
                            count(*) as LoveCount
                        from
                           Loves L
                        group by
                           L.PicID ) PreSum
           on p.id = PreSum.PicID
   order by
      PreSum.LoveCount DESC

答案 3 :(得分:0)

我相信您只需要加入数据并在您的选择中进行计数(*)。确保指定要用于ambigous列的表。此外,当您进行计数(*)时,不要忘记使用按功能分组。这是我在MS SQL上运行的示例查询。

Select CmsAgentInfo.LOGID, LOGNAME, hCmsAgent.SOURCEID, count(*) as COUNT from hCmsAgent
LEFT JOIN CmsAgentInfo on hCmsAgent.logid=CmsAgentInfo.logid
where SPLIT = '990'
GROUP BY CmsAgentInfo.LOGID, LOGNAME, hCmsAgent.SOURCEID

示例结果形式将是这样的。

77615   SMITH, JANE 1   36
29422   DOE, JOHN   1   648

希望有所帮助。祝你好运。