连接两个表时,按项目计数检索所有数据

时间:2013-10-12 11:06:57

标签: mysql sql database activerecord join

我有两张桌子:

Table 1: contest_video

Table Rows: cv_id, uid, cid, cn_id, video_name, video_detail, video, image, cverify, date

Table 2: contest_vote

Table Rows: vid, cv_id, voter_id, date

现在我想加入这两个计数器的表。与视频的总投票数(视频)一样(视频名称)

我试过这种方式:

SELECT *
FROM (`contest_video`)
  LEFT JOIN `system_user`
    ON `system_user`.`id` = `contest_video`.`uid`
  LEFT JOIN `contest_vote`
    ON `contest_vote`.`cv_id` = `contest_video`.`cv_id`
WHERE `contest_video`.`cid` = '1'
ORDER BY `contest_video`.`created_date` DESC

但它只返回数据而不计算。需要专家帮助。

1 个答案:

答案 0 :(得分:0)

你可以这样做

使用分组依据和列名而不是*

SELECT
  cv_id,
  uid,
  cid,
  cn_id,
  video_name,
  video_detail,
  video,
  image,
  cverify,
  date,
  count(`contest_video`.`cv_id`) Total
FROM (`contest_video`)
  LEFT JOIN `system_user`
    ON `system_user`.`id` = `contest_video`.`uid`
  LEFT JOIN `contest_vote`
    ON `contest_vote`.`cv_id` = `contest_video`.`cv_id`
WHERE `contest_video`.`cid` = '1'
GROUP BY `contest_video`.`video_name`
ORDER BY `contest_video`.`created_date` DESC