I use a mySQL query like this one to get some of the information I need about a photo:
SELECT
users.first_name,
users.last_name,
photos.filename,
photos.YEAR,
photos.description,
themes.name AS theme_name
FROM
`photos`,
`users`,
`themes`
WHERE
users.facebook_id = photos.author AND
themes.id = photos.theme AND
photos.id = 35
LIMIT 1;
I want to ‘SELECT’ one more piece of data with this query, ‘bookmarked’ which has a value of TRUE if the following query has exactly 1 row:
SELECT * FROM bookmarks WHERE photo_id = 35 and facebook_id = 19484;
Or else ‘bookmarked’ would have a value of FALSE.
Is this possible to do in a single query?
Edit – I changed Tadman’s solution slightly. Here it is, works perfectly!
SELECT
users.first_name,
users.last_name,
photos.filename,
photos.YEAR,
photos.description,
themes.name AS theme_name,
bookmarks.id AS bookmark
FROM
`photos`,
`users`,
`themes`
LEFT JOIN bookmarks ON bookmarks.photo_id = 35 AND bookmarks.facebook_id = 19484
WHERE
users.facebook_id = photos.author AND
themes.id = photos.theme AND
photos.id = 35
LIMIT 1;
This solution doesn’t set ‘bookmark’ equal to TRUE or FALSE, but I can work with NULL vs not NULL.
You could do a
LEFT JOINon this to pull the bookmark in if present. Ideally you’d have one and only one bookmark per photo per user maximum or you might have duplicated rows, one for each bookmark:The
LEFT JOINis an optional join, that is it may or may not succeed and if it fails it will leave the associated columns asNULL. You can check thatbookmarks.photo_idis defined and if so there’s a bookmark.Here
?represents the placeholder for thephotos.idcondition you’ve specified. Hopefully you’re using placeholders and proper SQL escaping for this query.