I have a SQL statement which is collating lots of info from several tables in my Android application, using SQLite3. Currently I have to insert the master id in several places, and I’d like to know if there’s a way to reduce this so that I only have to put the id in once (note – the id is being inserted where the question marks currently are – so can I reduce this so that I only have one question mark?):
SELECT m.movie_id, m.title, m.synopsis, m.review, m.certificate, m.duration, m.release_year, actors, directors, genres, video_url, video_title, video_thumbnail_url
FROM movies m
INNER JOIN
(
SELECT v.video_url as video_url, v.title as video_title, v.thumbnail_url as video_thumbnail_url, m.movie_id
FROM movies m
LEFT JOIN videos v
ON m.movie_id = v.movie_id
WHERE m.movie_id = ?
ORDER BY v.insert_order
LIMIT 1
) trailer_group
ON trailer_group.movie_id = m.movie_id,
(
SELECT movie_id, group_concat(name, ', ') actors
FROM
(
SELECT m.movie_id, a.name
FROM movies m
LEFT JOIN movie_actors a
ON m.movie_id = a.movie_id
WHERE m.movie_id = ?
ORDER BY m.movie_id, a.insert_order
)
) actor_group
ON actor_group.movie_id = m.movie_id,
(
SELECT movie_id, group_concat(name, ', ') directors
FROM
(
SELECT m.movie_id, d.name
FROM movies m
LEFT JOIN movie_directors d
ON m.movie_id = d.movie_id
WHERE m.movie_id = ?
ORDER BY m.movie_id, d.insert_order
)
) director_group
ON director_group.movie_id = m.movie_id,
(
SELECT movie_id, group_concat(name, ', ') genres
FROM
(
SELECT m.movie_id, g.name
FROM movies m
LEFT JOIN movie_genres g
ON m.movie_id = g.movie_id
WHERE m.movie_id = ?
ORDER BY m.movie_id, g.insert_order
)
) genre_group
ON genre_group.movie_id = m.movie_id
SQLLite syntax seems a bit off from what I’m used to, but you should be able to only list the predicate once:
Unless there’s something I’m missing, there should be no reason to list it multiple times.