Reputation: 2146
Up until today, this is the query that got everything I needed to know about a photo from my database:
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
However, now I'd like to also find out how many votes have been cast for this photo.
Here is my 'votes' table:
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 ;
And here is my attempt to modify my SQL query to fetch a vote count:
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
The above attempt resulted in this error:
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
Upvotes: 0
Views: 53
Reputation: 2146
The error was caused by a syntax problem. It was the asterix. This query performs properly and as desired:
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
Upvotes: 1