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

前端 未结 3 1547
野性不改
野性不改 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:44

    Try an outer join.

    SELECT TABLE_A.row_id, TABLE_A.category, TABLE_A.val_1, TABLE_B.val_2
    FROM TABLE_B
    LEFT OUTER JOIN TABLE_A ON TABLE_B.row_id = TABLE_A.row_id
    ORDER BY row_id;
    
    0 讨论(0)
  • 2021-01-13 11:50

    If you want all the results, you need an outer join, not an inner one. (Inner only returns the rows where there is a match; outer returns all rows, with the matching rows "stitched together")

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题