select from two tables where linked column can be null

倾然丶 夕夏残阳落幕 提交于 2020-01-04 09:16:07

问题


I have two tables in a database. Table 1 includes an order number which could be NULL. Table two contains all order data (including the order number).

Now I want to select all columns from table 1 and all order data from table two. So if a certain entry in table one doesn't contains this order number, all other columns should be null. But if it does contain an order number I want it to be linked to the second table and have these data selected.

Output should be something like:

column1tab1 column2tab1 order_number product amount
 xx            yy            123      p1      2
 xx            yy            456      p3      4
 xx            yy            NULL    NULL    NULL
 xx            yy            789      p2      1
 etc...

I tried different things, but I only get all the rows with an order number or all with null, but I can't get them both at the same time. Does someone know a solution, so I can do this in one query?


回答1:


what did you try? A simple left join would do the trick. Example:

select *
from orders o left join orderdata od on o.orderId=od.orderid



回答2:


 select t1.*
 from table1 as t1 right join table2 as t2  on t1.order_number=t2.order_number


来源:https://stackoverflow.com/questions/9763922/select-from-two-tables-where-linked-column-can-be-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!