问题
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