I have a database with games, articles (reviews + previews) and videos (video reviews + video previews). I have a game with id 233 and I want to find one review, one preview, one video review and video preview, if these are present.
To do this, I'm using the following query:
SELECT (SELECT article_url
FROM articles
WHERE articles_game_id = 233
AND artikel_sort = 'review'
AND article_online = 1
ORDER BY article_datetime DESC
LIMIT 1) AS review,
(SELECT article_url
FROM articles
WHERE articles_game_id = 233
AND artikel_sort = 'preview'
AND article_online = 1
ORDER BY article_datetime DESC
LIMIT 1) AS preview,
(SELECT trailer_url
FROM trailers
WHERE trailer_game_id = 233
AND trailer_sort = 'video review'
AND trailer_online = 1
ORDER BY trailer_datetime DESC
LIMIT 1) AS videoreview,
(SELECT trailer_url
FROM trailers
WHERE trailer_game_id = 233
AND trailer_sort = 'video preview'
AND trailer_online = 1
ORDER BY trailer_datetime DESC
LIMIT 1) AS videopreview
FROM articles
However, this query has two problems:
- It queries the database five times, which does not seem very efficient to me.
- If there is no review (for example), the resulting PHP array does have a key/value pair with the key 'review', but its value is empty. However, I would like this key/value pair to be totally absent, so I can simply loop over the array and print each key/value pair as a link.
Does anybody know an efficient way to solve this problem? Any help is greatly appreciated!
ORDER BY trailer_datetime DESC LIMIT 1