0

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

4 回答 4

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
于 2012-06-06T09:06:31.977 回答
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;
于 2012-06-06T09:07:19.650 回答
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
于 2012-06-06T09:08:57.623 回答
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 ;
于 2012-06-06T09:17:09.150 回答