I tried to get some data from a database, using MySQL JOIN, but with no success until now
I have table_a (representing order lines):
id idc cPos
1 1 10
2 1 20
3 1 30
4 1 40
5 1 50
6 2 10
7 2 20
8 2 30
9 2 40
10 3 10
11 3 20
12 3 30
13 3 40
14 3 50
And table_b:
delivery_id idc cPos
1 1 10
1 1 50
2 1 20
2 3 40
2 3 50
I would like a query with the below results:
id idc cPos delivery_id
1 1 10 1
3 1 30 NULL
4 1 40 NULL
5 1 50 1
6 2 10 NULL
7 2 20 NULL
8 2 30 NULL
9 2 40 NULL
10 3 10 NULL
11 3 20 NULL
12 3 30 NULL
I need all records from table_b where delivery_id equals 1 and all records from table_a that don't have a corespondent in table_b (by corespondent I understand table_a.idc = table_b.idc AND table_a.cPos = table_b.cPos)
The query used by me:
SELECT table_a.*, table_b.delivery_id FROM table_a
LEFT JOIN table_b ON (table_a.idc = table_b.idc AND table_a.cPos = table_b.cPos)
WHERE (delivery_id IS NULL OR delivery_id = 1)
Could someone help me?
You have to create LEFT JOIN with 2 conditions:
SELECT tab_a.*,tab_b.delivery_id
FROM table_a tab_a
LEFT JOIN table_b tab_b ON tab_a.idc=tab_b.idc, tab_a.cPos=tab_b.cPos
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.