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

后端 未结 4 712
误落风尘
误落风尘 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:51

    Try with UNION DISTINCT like:

    SELECT DISTINCT t1.id as ID,
            t2.company as Company,
            'FOUND' AS status
     FROM   table1 t1
            JOIN table2 t2
              ON t1.id = t2.id
    group by ID
    
    union distinct
    
    SELECT DISTINCT t2.id as ID,
            t2.company as Company,
            'FOUND' AS status
     FROM   table1 t1
            JOIN table2 t2
              ON t1.name = t2.name
    group by ID
    
    union distinct
    
    SELECT t1.name as ID,
            t1.name as Company,
            'NOT FOUND' AS status
     FROM   table1 t1
      WHERE  t1.name NOT IN (SELECT t2.name
                                    FROM   table2 t2)
    GROUP BY ID
    

提交回复
热议问题