连接两个表(其中一个是另一个表的一部分)

时间:2012-06-06 09:00:45

标签: mysql join

我有两个表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        | 
+-----------+-----------+

Table_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 )

4 个答案:

答案 0 :(得分:0)

你可以尝试:

SELECT tb.tableB_id, tb.s_name, ta.tableA_id, ta.v_id
FROM Table_B tb LEFT JOIN Table_A ta
  ON tb.tableB_id = ta.tableB_id

只选择一个可以使用的:

SELECT tb.tableB_id, tb.s_name, ta.tableA_id, ta.v_id
FROM Table_B tb LEFT JOIN 
(SELECT * FROM Table_A 
 WHERE v_id = 27) ta
  ON tb.tableB_id = ta.tableB_id

答案 1 :(得分:0)

SELECT distinct s.tableB_id, s.s_name, v.tableA_id, v.v_id
 FROM Table_A as v 
 left OUTER JOIN Table_B as s
 ON v.tableB_id =s.tableB_id and v.v_id = 27;

答案 2 :(得分:0)

使用此查询希望完全得到结果

SELECT s.tableB_id, s.s_name, v.tableA_id, v.v_id
FROM Table_A as v 
left OUTER JOIN Table_B as s ON s.tableB_id=v.tableB_id
WHERE v.v_id=27

答案 3 :(得分:0)

撤销订单,将其设为b LEFT JOIN a并添加公共列(tableB_id)的条件:

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.tableB_id = s.tableB_id
    AND v.v_id=27 ;