PostgreSQL - 合并两个选择查询

时间:2015-05-04 20:49:55

标签: sql postgresql

我有两张桌子:

公司 用户

用户表:

    id   |   name   |   cpf     |   phone_number  | company_id

    1    |   Jonh   | 111.11.11 |   1111-1111     |    1

    2    |   Marie  | 222.22.22 |   2222-2222     | 

    3    |   Paul   | 333.33.33 |   3333-3333     |    3

    4    |   Luna   | 444.44.44 |   4444-4444     |    1

    5    |   Leo    | 555.55.55 |   5555-5555     |    

公司表:

id   |   name       |   cnpj      |   phone_number | company_data | consumer

1    |  companyA    | 111.1111.11 |   1111-1111    |     data1    | true

2    |  companyB    | 222.2222.22 |   2222-2222    |     data2    | true

3    |  companyC    | 333.3333.33 |   3333-3333    |     data3    | false

我想选择company_id IS NULL和所有公司的所有用户 其中consumer is true

我尝试做的事情是这样的:

 Select u.name as name,
          u.cpf as document,
          u.phone_number as phoneNumber,
          'false' as company
          FROM users u 
          WHERE company_id is NULL

   UNION

   Select c.name as name,
          c.cnpj as document, 
          c.phone_number as phoneNumber,
          c.company_data as companyData
          'true' as company
          FROM company c
          WHERE c.consumer = 'true'

  ORDER BY id

我想要的答案是:

id   |   name       |   document  |   phone_number  | companyData |  company

1    |  companyA    | 111.1111.11 |   1111-1111     |   data 1    |   true

2    |  companyB    | 222.2222.22 |   2222-2222     |   data 2    |   true

2    |   Marie      | 222.22.22   |   2222-2222     |             |  false

5    |   Leo        | 555.55.55   |   5555-5555     |             |  false

我可以接受列cpfcnpj的答案,如果结果适用于所选实体,则结果为空。这样我就不需要company

3 个答案:

答案 0 :(得分:1)

两个选择都需要相同数量的列,只需添加一个NULL列(您可能必须将其转换为数据类型):

   Select u.name as name,
          u.cpf as document,
          u.phone_number as phoneNumber,
          CAST(NULL AS VARCHAR(20)) as companyData,
          'false' as company
          FROM users u 
          WHERE company_id is NULL

   UNION

   Select c.name as name,
          c.cnpj as document, 
          c.phone_number as phoneNumber,
          c.company_data as companyData
          'true' as company
          FROM company c
          WHERE c.consumer = 'true'

  ORDER BY id

答案 1 :(得分:0)

根据上述......

Select CASE WHEN users.company_id is NULL THEN users.name ELSE company.name ...
  ... FROM users JOIN company ON(users.company_id = company.id)
  ...

答案 2 :(得分:0)

如果userscompany具有相同的列,则可以使用联合查询

select u.name, null from users where company_id is null
union
select c.name, c.some_column from users u 
join company c on u.company_id = c.id

如果它们没有相同的列,则必须手动指定要选择的列名,而不是选择*