使用COUNT()查找另一个表中存在的行数

时间:2012-10-11 20:42:46

标签: mysql sql database

到目前为止,这是我的数据库中关于照片的一切查询:

SELECT
      users.facebook_id,
      users.first_name,
      users.last_name,
      photos.*,
      bookmarks.photo_id AS bookmark
FROM
      photos
JOIN users
      ON photos.author = users.facebook_id
LEFT JOIN bookmarks
    ON photos.id = bookmarks.photo_id
    AND bookmarks.facebook_id = 123456789
WHERE photos.description <> ''
ORDER BY photos.id DESC

但是现在,我想再收到一条信息。我想知道在一张特定照片上投了多少票。

这是我的投票表:

CREATE TABLE IF NOT EXISTS `votes` (
  `photo_id` int(11) NOT NULL,
  `facebook_id` bigint(20) NOT NULL COMMENT 'The user''s Facebook ID.',
  `date` varchar(10) NOT NULL COMMENT 'Date formatted as YYYY-MM-DD.',
  UNIQUE KEY `one_vote_per_day` (`photo_id`,`facebook_id`,`date`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

以下是我的尝试:

SELECT
      count(votes.photo_id) as vote_count,
      users.facebook_id,
      users.first_name,
      users.last_name,
      photos.*,
      bookmarks.photo_id AS bookmark
FROM
      photos
JOIN users
      ON photos.author = users.facebook_id
LEFT JOIN votes
    ON votes.id = photos.photo_id
LEFT JOIN bookmarks
    ON photos.id = bookmarks.photo_id
    AND bookmarks.facebook_id = 123456789
WHERE photos.description <> ''
ORDER BY photos.id DESC

显然我做错了,因为当我尝试这个时,我的结果永远不会超过一张照片。

当我只需要有关单张照片的信息时,此方法适用于我,但此查询需要同时适用于所有照片......

2 个答案:

答案 0 :(得分:3)

您需要group by

SELECT
      count(votes.photo_id) as vote_count,
      users.facebook_id,
      users.first_name,
      users.last_name,
      --photos.*, you have to add all fileds you need, and add them to group by
      bookmarks.photo_id AS bookmark
FROM
      photos
JOIN users
      ON photos.author = users.facebook_id
LEFT JOIN votes
    ON votes.id = photos.photo_id
LEFT JOIN bookmarks
    ON photos.id = bookmarks.photo_id
    AND bookmarks.facebook_id = 123456789
WHERE photos.description <> ''
group by users.facebook_id,
         users.first_name,
         users.last_name,
         bookmarks.photo_id
ORDER BY photos.id DESC

答案 1 :(得分:0)

不确定MySQL是否支持SELECT中的嵌套查询,但请尝试以下方法:

SELECT
      users.facebook_id,
      users.first_name,
      users.last_name,
      photos.*,
      bookmarks.photo_id AS bookmark,
      (select count(*) from votes where votes.photo_id = photo.id) AS number_of_votes
FROM
      photos
JOIN users
      ON photos.author = users.facebook_id
LEFT JOIN bookmarks
    ON photos.id = bookmarks.photo_id
    AND bookmarks.facebook_id = 123456789
WHERE photos.description <> ''
ORDER BY photos.id DESC