使用具有连接

时间:2016-08-09 14:45:18

标签: mysql sql join subquery

我正在使用子查询来过滤表,但是它还连接了另一个我需要其值的表:

SELECT * FROM properties
JOIN (
  SELECT persons.*, cities.* FROM persons
  JOIN properties.* ON properties.person_id = persons.id
    AND (properties.value = 1 OR properties.value = 2)
  JOIN cities ON cities.id = persons.city_id
  GROUP BY persons.id
  HAVING COUNT(DISTINCT properties.id) = 2
) filtered_persons ON filtered_persons.id = properties.person_id

在命名子查询persons.id时由cities.idfiltered_persons引起的冲突。子查询实际上来自PHP代码中的函数调用,否则我将稍后加入cities

结果是具有特定属性集的那些人的所有属性的列表。

生成的查询应包含properties.*persons.*cities.*,因为稍后会将其用于进一步过滤。

如何在不更改子查询的情况下避免命名冲突?它有可能吗?

2 个答案:

答案 0 :(得分:0)

您需要创建别名,根据别名,您可以设置条件。喜欢 SELECT * FROM users as userTable INNER JOIN clients as client on user ON userTable.id = clients.id;

答案 1 :(得分:0)

您的代码可以正常工作,您应该为城市,人员表使用别名。 由于您的(id)列不明确。 person.id和cities.id列具有相同的id列名。有两个表人和城市表具有相同名称列的id。因此,使用列名称的别名来获取值。

    SELECT * FROM properties
JOIN (
  SELECT p.id as personid , c.id as id FROM persons as p
  JOIN properties as properties ON properties.person_id = p.id
    AND (properties.value = 1 OR properties.value = 2)
  JOIN cities as c ON c.id = p.city_id
  GROUP BY p.id
  HAVING COUNT(DISTINCT properties.id) = 2
) filtered_persons ON filtered_persons.id = properties.person_id