如何使用1个查询从多个表中获取所有行

时间:2017-04-02 11:21:23

标签: sql

我有4个表(电影,系列,列表和list_titles),问题是:如何将所有电影,系列附加到list_titles表中的特定列表?

以下是我所做的sqlfiddle

查询:

select *
from (
    select srs.*
    from series srs
    left join list_titles lt on lt.type_id = srs.id
    where lt.list_id = 7
        and lt.type_name = 'series'
        and lt.user_id = 1
    ) as a,
    (
        select mo.*
        from movies mo
        left join list_titles tl on tl.type_id = mo.id
        where tl.list_id = 7
            and tl.type_name = 'series'
            and tl.user_id = 1
        ) as b

2 个答案:

答案 0 :(得分:0)

您希望在两个查询之间使用UNION ALL

select s.id,
    s.title_name,
    ...
from series s
left join list_titles lt on lt.type_id = s.id
where lt.list_id = 7
    and lt.type_name = 'series'
    and lt.user_id = 1

union all

select m.id,
    m.title_name,
    ...
from movies m
left join list_titles tl on tl.type_id = m.id
where tl.list_id = 7
    and tl.type_name = 'series'
    and tl.user_id = 1

Demo

答案 1 :(得分:0)

select * from
(
  select srs.id, srs.title_name from series srs join 
    (
    select * from list_titles
      where list_id = 7 and type_name = 'series' and user_id = 1
    ) as part1
  on part1.type_id = srs.id
) as a

union

select * from
(
  select mo.id, mo.title_name from movies mo join 
    (
    select * from list_titles
      where list_id = 7 and type_name = 'series' and user_id = 1
    ) as part2
  on part2.type_id = mo.id
) as b;