I have two tables Table_A and Table_B and i want to join those tables to optain Table_c as the result:
Table_A:
+-----------+-----------+---------+
| tableA_id | tableB_id | v_id |
+-----------+-----------+---------+
| 1 | 2 | 27 |
| 2 | 3 | 27 |
| 3 | 3 | 28 |
| 4 | 1 | 26 |
| 5 | 2 | 26 |
| 6 | 3 | 26 |
| 7 | 1 | 24 |
| 8 | 1 | 25 |
+-----------+-----------+---------+
Table_B:
+-----------+-----------+
| tableB_id | s_name |
+-----------+-----------+
| 1 | s1 |
| 2 | s2 |
| 3 | s3 |
+-----------+-----------+
Table_c:
+-----------+-----------+-----------++--------+
| tableB_id | s_name | tableA_id | v_id |
+-----------+-----------+-----------+---------+
| 1 | s1 | null | null |
| 2 | s2 | 1 | 27 |
| 3 | s3 | 2 | 27 |
+-----------+-----------+-----------+---------+
I tried different queries, but i couldn’t reach the desired output.
This is MYSQL query: *Edit: reverse table order.
SELECT s.tableB_id, s.s_name, v.tableA_id, v.v_id
FROM Table_B as s
left OUTER JOIN Table_A as v
ON v.v_id=27
EDIT:
The result should be all Table_B data on left and assign to it table_A data if any or make it null. How can i make this?
Last Edit:
Here is a solution i came up with:
SELECT s.tableB_id , s.s_name, v.tableA_id, v.v_id
FROM Table_B s , Table_A v
WHERE v.v_id=27 AND v.tableB_id = s.tableB_id
UNION
SeLECT s.tableB_id , s.s_name, null as tableA_id, null as v_id
FROM Table_B s
WHERE s.tableB_id NOT IN (SELECT s.tableB_id
FROM Table_B s , Table_A v
WHERE v.v_id=27 AND v.tableB_id = s.tableB_id )
You could try:
To choose only one you could use: