我有四个表,如下:
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处租用房产的租户的列表。
当我运行如下查询时:
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我得到了重复的行:
+----+------------+
| id | name |
+----+------------+
| 1 | John Smith |
| 1 | John Smith |
+----+------------+我知道将查询更改为
SELECT
DISTINCT tenant.id, tenant.name ...将删除重复的行,但我的问题是:
有没有可能避免使用DISTINCT和构造连接,这样就不会返回重复的行?我已经尝试过INNER,LEFT JOINS的所有组合,但没有太多机会:(
非常感谢您的任何建议
发布于 2011-11-26 22:06:13
Jonh Smith是Best Homes的两处房产的租户,所以他出来了两次,所以你必须处理group by或distinct等。
为了得到你想要的东西,你需要另外一张表,比如
投资组合,这将给你一个记录连接帐篷到kandlord。然后,您可以使用它将投资组合与属性联系起来。例如,您将多个租户组合在一起,因此您不必使用tennat_has_property表来查看关系。
我不知道是否值得对模式进行重构。
发布于 2011-11-26 19:45:40
真正的版本是
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服务器。
https://stackoverflow.com/questions/8278152
复制相似问题