How can I query for all records in a table called photos, and know which of the resulting photos have been bookmarked by the current user using a single query?
Here are my tables:
--
-- Table structure for table `photos`
--
CREATE TABLE IF NOT EXISTS `photos` (
`id` int(11) NOT NULL auto_increment,
`author` bigint(20) NOT NULL COMMENT 'The user''s Facebook ID.',
`filename` varchar(255) NOT NULL,
`thumbnail` varchar(255) NOT NULL,
`post_date` timestamp NOT NULL default CURRENT_TIMESTAMP,
`description` varchar(140) NOT NULL,
`finalist` tinyint(4) NOT NULL DEFAULT '0',
CONSTRAINT user_must_exist FOREIGN KEY (author)
REFERENCES users(facebook_id)
ON DELETE CASCADE,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Table structure for table `bookmarks`
--
CREATE TABLE IF NOT EXISTS `bookmarks` (
`facebook_id` bigint(20) NOT NULL COMMENT 'The author''s Facebook ID.',
`photo_id` int(11) NOT NULL,
CONSTRAINT photo_should_exist FOREIGN KEY (photo_id)
REFERENCES photos(id)
ON DELETE CASCADE,
CONSTRAINT user_should_exist FOREIGN KEY (facebook_id)
REFERENCES users(facebook_id)
ON DELETE CASCADE,
UNIQUE KEY `no_duplicates` (`facebook_id`,`photo_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='The user''s favourite photos.';
I would imagine this query would look something like the following:
SELECT
photos.*,
bookmarks.photo_id AS bookmark
FROM photos
LEFT JOIN bookmarks
ON bookmarks.photo_id = photos.id
AND photos.author = 123456789
However this doesn’t work and I receive the following MySQL error:
Unknown column 'photos.id' in 'on clause'
keyur’s code worked for me after a minor typo fix which Barmar pointed out.
SELECT photos . * , bookmarks.photo_id AS bookmark
FROM photos
LEFT JOIN bookmarks ON photos.id = bookmarks.photo_id
AND bookmarks.facebook_id = 123456789
Thank you.
Editted for typo.
Editted for second typo.
you query should be like this.
according your table structure
photos.facebook_idis not exist; it is in bookmarks table