加入来自A的每条记录,其中特定的B.id来自B,其中B.id =?

时间:2012-10-05 15:00:16

标签: mysql

我有两张桌子,A和B.

A的字段:id,name

-----------------
 ID |   NAME    |
-----------------
 1  |   name1   |
-----------------
 2  |   name2   |
-----------------
 3  |   name3   |
-----------------
 4  |   name4   |
-----------------
 5  |   name5   |
-----------------

B的字段:bid,id

-----------------
 BID    |   ID  |
-----------------
 11     |   1   |
-----------------
 11     |   2   |
-----------------
 12     |   1   |
-----------------
 12     |   2   |
-----------------
 12     |   3   |
-----------------

我想执行查询以显示A中的所有记录,左侧是A.id,A.name列。并加入B ON id WHERE bid = '11'的第三列。

所以我会有这样的事情:

--------------------------------
 A.ID   |   A.NAME  |   B.BID
--------------------------------
 1      |   name1   |   11
--------------------------------
 2      |   name2   |   11
--------------------------------
 3      |   name3   |
--------------------------------
 4      |   name4   |
--------------------------------
 5      |   name5   |
--------------------------------

有什么建议吗?

3 个答案:

答案 0 :(得分:3)

您需要使用LEFT JOIN

SELECT A.ID, A.NAME, B.BID
FROM A
LEFT JOIN B
   ON A.id = B.id
WHERE B.BID = yourValue -- use the WHERE clause for additional filtering

请参阅SQL Fiddle With Demo

根据您的更新,您需要将过滤器从WHERE子句移至JOIN

SELECT A.ID, A.NAME, IFNULL(B.BID, '') BID
FROM A
LEFT JOIN B
   ON A.id = B.id
  and b.bid = 11

请参阅SQL Fiddle with Demo

答案 1 :(得分:2)

列出所有值,无论bid的值是否为left join

select a.id, a.name, b.bid
from a
left join b on b.id = a.id
where b.bid = 11

如果inner join具有特定值,请使用bid

select a.id, a.name, b.bid
from a
inner join b on b.id = a.id
where b.bid = 11

Good explanation of joins

SQLFiddle example

答案 2 :(得分:1)

table_B中的列是否包含与table_A中的a.id相同的值?如果没有,您将无法将table_b连接到table_a。你需要的是

WHERE bid = ? 

应该像

WHERE bid = a.bid

OR

WHERE a.ID = b.AID