1

到目前为止,这是一个让我想知道关于数据库中照片的所有信息的查询:

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

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

当我只需要一张照片的信息时,这种方法对我来说很好,但是这个查询需要同时适用于所有照片......

4

2 回答 2

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
于 2012-10-11T20:47:31.277 回答
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
于 2012-10-11T20:46:37.860 回答