开发者

Joining Tables With the Possibility of No Matching Value on the Other One

开发者 https://www.devze.com 2023-04-01 01:35 出处:网络
I have 2 tables that I want to join. Table A ------------开发者_开发百科 owner | id | ------------

I have 2 tables that I want to join.

      Table A
    ------------开发者_开发百科
   | owner | id |
    ------------
   |  a   |  1  |  
   |  a   |  2  |
     ..........
   |  a   |  20 |
    ------------

        Table B
    ---------------
   | a_id | number |
    ---------------
   |  1   |   2    |
   |  2   |   7    |
     .............
   |  15  |   3    |
    ---------------

How can I join those two tables, showing all of the records from Table A and ordering them by number from Table B? The total number of records in Table A and Table B is not always the same. Most of the time, Table A will have a few records (about 1 - 3) more than Table B.

I tried using a query with a WHERE clause that will check if id is equal to a_id or a_id is equal to NULL but it doesn't work. The result was, only id that exist in Table B (the a_id column) shows up.


Use LEFT JOIN if you want to return a row even if there is no matching row in the joined table:

SELECT     *
FROM       A
LEFT JOIN  B ON B.a_id = A.id
ORDER BY   B.number

The columns of the joined table will be NULL when there was no match row.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号