sql how to combine three queries from two tables into one query

后端 未结 4 896
误落风尘
误落风尘 2021-01-23 02:36

i have the following two tables:

Table1

id  name
---------
A3  B2
A3  B400
A5  B100
A7  B200
A8  B6
A8  B2
A8  B3

and

4条回答
  •  情书的邮戳
    2021-01-23 02:59

    There's something unclear about your queries, because they shouldn't execute as you've shown them (due to select containing non-aggregates not in group by). But based on your explanation of what you're trying to do...

    You could use outer joins and then use case logic and/or coalesce to determine which value to use in each case.

    SELECT DISTINCT
           coalesce(t2_id.id, t2_name.id, t1.name) as ID
         , coalesce(t2_id.company, t2_name.company, t1.name) as Conpany
         , case when t2_id.id is not null or t2_name.name is not null
                then 'FOUND'
                else 'NOT FOUND'
           end status
      FROM           table1 t1
           LEFT JOIN table2 t2_id
                  ON t1.id = t2_id.id
           LEFT JOIN table2 t2_name
                  ON t1.name = t2_name.name
    

    Note that I used DISTINCT to make sure the exact same row doesn't appear multiple times; but this may return multiple rows for an ID (with different Company values) depending on the data. I couldn't quite tell what was intended because the uses of DISTINCT and GROUP BY in the three queries as posted in the question didn't seem to add up for me.

提交回复
热议问题