MySQL初学者加入查询

时间:2011-08-08 11:45:10

标签: mysql join

架构:tblCusotmers存储客户,tblAddresses存储其地址,每个客户有很多地址;

tblCustomers customer_id:1 名称:XYZ Corp

tblAddresses address_id:1 customer_id:1

address_id:2 customer_id:1

address_id:3 customer_id:1

我希望,在给定地址ID的情况下,检索属于同一客户的地址的所有地址ID。因此,鉴于上面的示例,给定地址ID 3,我希望返回数字1,2和3。

我确信这是一个简单的联接,但我一直在尝试并尝试在脑海中解决它而不能。有人可以让我感到羞耻吗?

2 个答案:

答案 0 :(得分:3)

JOIN是工作的工具。一般来说,子查询只应用于执行无法通过JOIN执行的操作。

这应该是获得所需内容的最佳方式(确保tblAddresses.customer_id上有索引):

SELECT t2.id
FROM tblAddresses AS t1
JOIN tblAddresses AS t2 ON t2.customer_id = t1.customer_id
WHERE t1.address_id = 3

答案 1 :(得分:2)

SELECT * 
FROM tblAddresses 
WHERE customer_id = (SELECT customer_id FROM tblAddresses WHERE address_id=3)

这使用子查询来获取正确行的customer_id,并在where子句中使用它。 MySQL Docs on subqueries

使用JOIN(稍微复杂一些,但正如您特别要求的那样):

SELECT t1.*
FROM tblAddresses AS t1
INNER JOIN (SELECT customer_id FROM tblAddress WHERE address_id=3) AS t2
ON t1.customer_id = t2.customer_id