首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >多表联接中的重复行

多表联接中的重复行
EN

Stack Overflow用户
提问于 2011-11-26 19:39:23
回答 2查看 1.7K关注 0票数 2

我有四个表,如下:

代码语言:javascript
复制
tenant
+----+------------+
| id | name       |
+----+------------+
|  1 | John Smith | 
|  2 | Anna Jones | 
+----+------------+

property
+----+-------------+---------------+
| id | landlord_id | address       |
+----+-------------+---------------+
|  1 |           1 | King Street 1 | 
|  2 |           1 | Green Grove 2 | 
|  3 |           2 | Queen Stree 3 | 
+----+-------------+---------------+

tenant_has_property
+-----------+-------------+
| tenant_id | property_id |
+-----------+-------------+
|         1 |           1 | 
|         1 |           2 | 
+-----------+-------------+

landlord
+----+-----------------+
| id | name            |
+----+-----------------+
|  1 | Best Homes Ltd. | 
|  2 | RealEstates Inc | 
+----+-----------------+

现在,我想获取所有从房东id =1处租用房产的租户的列表。

当我运行如下查询时:

代码语言:javascript
复制
SELECT 
  tenant.id, tenant.name 
FROM 
  tenant, property, tenant_has_property 
WHERE 
  tenant.id = tenant_has_property.tenant_id AND 
  tenant_has_property.property_id = property.id AND 
  property.landlord_id = 1

我得到了重复的行:

代码语言:javascript
复制
+----+------------+
| id | name       |
+----+------------+
|  1 | John Smith | 
|  1 | John Smith | 
+----+------------+

我知道将查询更改为

代码语言:javascript
复制
SELECT 
  DISTINCT tenant.id, tenant.name ...

将删除重复的行,但我的问题是:

有没有可能避免使用DISTINCT和构造连接,这样就不会返回重复的行?我已经尝试过INNER,LEFT JOINS的所有组合,但没有太多机会:(

非常感谢您的任何建议

EN

Stack Overflow用户

发布于 2011-11-26 19:45:40

真正的版本是

代码语言:javascript
复制
SELECT id, name FROM tenant 
WHERE id IN 
(SELECT tenant_has_property.tenant_id FROM 
tenant_has_property 
WHERE tenant_has_property.property_id IN 
(SELECT property.id FROM property WHERE property.landlord_id = 1 )
)

我想这对你来说应该很管用。但我没有尝试,因为我无法在我的终端上访问sql服务器。

票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8278152

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档