直到今天,这是一个查询,我需要知道我的数据库中的照片:
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
答案 0 :(得分: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