使用mysql查询从表中选择所有行,并在另一个表中指示存在

时间:2017-02-05 10:57:35

标签: mysql

我有三张桌子

Table a
+-----+-------+
| aid | value |
+-----+-------+
|   1 | A     |
|   2 | B     |
|   3 | C     |
|   4 | D     |
+-----+-------+

Table b
+-----+------+
| bid | name |
+-----+------+
|   1 | A    |
|   2 | B    |
|   3 | C    |
+-----+------+

Table ba (mapping of table a and table b)
+-----+-----+
| bid | aid |
+-----+-----+
|   1 | 1   |
|   2 | 1   |
|   3 | 1   |
|   3 | 2   |
|   1 | 3   |
|   2 | 3   |
|   2 | 4   |
+-----+-----+

从这些表中我想要一个像

这样的查询
SELECT aid, mapped('true'-if(aid exist in ba) 'false'-otherwise) 
FROM a 
     JOIN b 
     JOIN ba 
WHERE bid=1

从我可以生成列表的位置获取结果

(when bid=1)
A-mapped
B-not mapped
C-mapped
D-not mapped

(when bid=2)
A-mapped
B-not mapped
C-mapped
D-mapped

(when bid=3)
A-mapped
B-mapped
C-not mapped
D-not mapped

现在我正在while循环中为表格的所有行生成列表' a'在循环内部,每次迭代都会执行一个查询,以检查表格中是否存在。

1 个答案:

答案 0 :(得分:0)

这是一个棘手的问题,但困难的部分在于弄清楚如何制定查询。一旦完成,它就会从那里走下坡路。一种方法是使用A和B表之间的交叉连接来获得所有可能的映射。然后LEFT JOIN到映射表以确定哪些对被映射,哪些不被映射。请尝试以下查询:

SELECT tb.bid, ta.value,
       CASE WHEN ba.bid IS NOT NULL THEN 'mapped' ELSE 'not mapped' END AS label
FROM tb INNER JOIN ta     -- cross join to obtain all bid/aid pairs
LEFT JOIN ba              -- to determine which pairs are mapped/not mapped
    ON ta.aid = ba.aid AND tb.bid = ba.bid
ORDER BY tb.bid, ta.value

在这里演示:

SQLFiddle