How can I join two tables with different number of rows in MySQL?

前端 未结 3 1553
野性不改
野性不改 2021-01-13 11:00

I have two tables which I want to connect.

TABLE_A:

+-----------+-----------+---------+
| row_id    | category  | val_1   |
+-----------+----------         


        
3条回答
  •  醉梦人生
    2021-01-13 11:50

    This ought to do it:

    SELECT 
      TABLE_B.row_id row_id, 
      TABLE_A.category category, 
      COALESCE(TABLE_A.val_1,1) val_1,
      TABLE_B.val_2 val_2
    FROM TABLE_A
    RIGHT OUTER JOIN TABLE_B 
      ON TABLE_B.row_id = TABLE_A.row_id
    ORDER BY TABLE_B.row_id;
    

    The RIGHT OUTER JOIN pulls all the records from Table_B even if they don't exist in Table_A, and the COALESCE statement is a function that returns its first non-NULL parameter. In this case, if there is no value in Table_A, it will return 1, which is what your example result lists as the desired output.

提交回复
热议问题