我有两个表 Table_A 和 Table_B ,我想加入这些表来选择 Table_c 作为结果:
表_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 |
+-----------+-----------+---------+
表_B:
+-----------+-----------+
| tableB_id | s_name |
+-----------+-----------+
| 1 | s1 |
| 2 | s2 |
| 3 | s3 |
+-----------+-----------+
表_c:
+-----------+-----------+-----------++--------+
| tableB_id | s_name | tableA_id | v_id |
+-----------+-----------+-----------+---------+
| 1 | s1 | null | null |
| 2 | s2 | 1 | 27 |
| 3 | s3 | 2 | 27 |
+-----------+-----------+-----------+---------+
我尝试了不同的查询,但无法达到所需的输出。这是 MYSQL 查询:*编辑:反转表顺序。
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
编辑: 结果应该是左侧的所有 Table_B 数据,并分配给它 table_A 数据(如果有)或使其为空。我怎么能做这个?
最后编辑: 这是我想出的解决方案:
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 )