在具有多个SELECTS的SQL语句中,如何仅将主ID设置一次?

时间:2011-11-23 11:27:59

标签: sql sqlite

我有一个SQL语句,它使用SQLite3整理Android应用程序中几个表的大量信息。目前我必须在几个地方插入主ID,我想知道是否有办法减少这个,所以我只需要将id放入一次(注意 - id正在插入当前问号的位置是 - 所以我可以减少这个,这样我只有一个问号吗?):

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

1 个答案:

答案 0 :(得分:0)

SQLLite语法似乎与我习惯的有点不同,但你应该只能列出谓词一次:

SELECT * from movies m
LEFT JOIN videos v ON v.movie_id = m.movie_id
LEFT JOIN actors a ON a.movie_id = m.movie_id
...
WHERE m.movie_id = ?

除非有我遗漏的东西,否则没有理由多次列出它。