MySQL - JOIN a OR b

后端 未结 3 1427
猫巷女王i
猫巷女王i 2021-01-17 02:43

Let\'s say I have a TABLE a in which a COLUMN data is the one to join on for 2 other tables (TABLE b and TABLE

相关标签:
3条回答
  • 2021-01-17 03:36

    If data is guaranteed to be UNIQUE in tables b and c

    We can use outer join to attempt to get matching row from each of the tables, and then use expression in the SELECT list to test whether we got a matching row. For example:

    SELECT a.data
         , IF(b.data IS NULL,IF(c.data IS NULL,NULL,'c'),'b') AS info_src
         , IF(b.data IS NULL,c.info,b.info) AS b_or_c_info
      FROM a
      LEFT
      JOIN b 
        ON b.data = a.data
      LEFT
      JOIN c
        ON c.data = a.data
    

    If we find a matching row in b, then b.data is guaranteed to be non-NULL. We know the value is non-NULL because it satisfied an equality (=) comparison.

    Note that IF is MySQL specific syntax. A more portable ANSI-standards compliant version

           CASE
             WHEN b.data IS NULL
             THEN c.info
             ELSE b.info
           END  AS b_or_c_info
    
    0 讨论(0)
  • 2021-01-17 03:42

    You can left join to both of the b and c tables, then use whichever info field is not NULL:

    select coalesce(b.info, c.info) info
    from a
      left join b on a.data = b.data
      left join c on a.data = c.data
    
    0 讨论(0)
  • 2021-01-17 03:46

    Try something like this:

    SELECT IFNULL(b.info,c.info) AS info
    FROM a
        LEFT JOIN b ON a.data = b.data
        LEFT JOIN c ON a.data = c.data
    
    0 讨论(0)
提交回复
热议问题