0

直到今天,这个查询从我的数据库中得到了我需要知道的关于一张照片的所有信息:

SELECT 
    users.facebook_id, 
    users.first_name, 
    users.last_name, 
    photos.filename, 
    photos.description, 
    photos.finalist, 
    bookmarks.photo_id AS bookmark 
FROM `photos`, `users` 
LEFT JOIN bookmarks ON bookmarks.photo_id = 123 AND bookmarks.facebook_id = 123456789 
WHERE 
    users.facebook_id = photos.author AND 
    photos.id = 123 
LIMIT 1

但是,现在我还想知道这张照片有多少票。

这是我的“投票”表:

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 ;

这是我尝试修改我的 SQL 查询以获取投票计数:

SELECT 
    users.facebook_id, 
    users.first_name, 
    users.last_name, 
    photos.filename, 
    photos.description, 
    photos.finalist, 
    bookmarks.photo_id AS bookmark,
    count(votes.*) AS vote_count
FROM `photos`, `users` 
LEFT JOIN votes ON votes.photo_id = 123  
LEFT JOIN bookmarks ON bookmarks.photo_id = 123 AND bookmarks.facebook_id = 123456789 
WHERE 
    users.facebook_id = photos.author AND 
    photos.id = 123 
LIMIT 1

上述尝试导致此错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*) AS vote_count FROM `photos`, `users` LEFT JOIN votes ON votes.photo_id = 1' at line 9
4

1 回答 1

1

该错误是由语法问题引起的。那是星号。此查询按需要正确执行:

SELECT 
    users.facebook_id, 
    users.first_name, 
    users.last_name, 
    photos.filename, 
    photos.description, 
    photos.finalist, 
    bookmarks.photo_id AS bookmark,
    count(votes.photo_id) AS vote_count
FROM `photos`, `users` 
LEFT JOIN votes ON votes.photo_id = 123  
LEFT JOIN bookmarks ON bookmarks.photo_id = 123 AND bookmarks.facebook_id = 123456789 
WHERE 
    users.facebook_id = photos.author AND 
    photos.id = 123 
LIMIT 1
于 2012-10-05T06:47:07.053 回答