SQL - 使JOIN查询复杂化

时间:2012-08-30 21:18:15

标签: php mysql sql join

在教程中我看到了这个SQL查询:

SELECT a.id as a_id, a.info as a_info, 
       b.id as b_id, b.info as b_info 
FROM stats AS a 
JOIN stats as b
ON a.id != b.id 
LIMIT 25

查询运行良好,但现在我需要添加 WHERE 条件。我有表users。表格stats包含列user_id。 如果stats(例如),我尝试从表users.city=1中获取所有用户,但我仍然无法找到方法,如何实现...

我的问题是,我目前不知道如何将查询放入另一个JOIN(对于表users)。

我很感激你的每一条建议,谢谢

4 个答案:

答案 0 :(得分:1)

所以这就是你所拥有的......

这是你的回归

SELECT a.id as a_id, a.info as a_info, b.id as b_id, b.info as b_info 

这是它来自

FROM stats AS a 
JOIN stats as b on a.id != b.id 

这是你想要的数量

LIMIT 25

因此,如果您要添加users表,请在另一个加入后添加

JOIN users ON a.user_id = users.id

并过滤它,在连接后添加

WHERE users.city=1

给予

SELECT a.id as a_id, a.info as a_info, b.id as b_id, b.info as b_info 
FROM stats AS a 
JOIN stats as b on a.id != b.id 
JOIN users ON a.user_id = users.id
WHERE users.city=1
LIMIT 25

答案 1 :(得分:1)

为方便起见,我重新格式化了原始的SQL语句,使其可供人类阅读。

SELECT a.id   AS a_id
     , a.info AS a_info
     , b.id   AS b_id
     , b.info AS b_info
  FROM stats a
  JOIN stats b
    ON a.id != b.id 
 LIMIT 25

您当前的查询几乎返回笛卡尔积。统计数据中的每一行都与统计数据中的每一行匹配,但匹配自身除外。 (假设stats.id是主键或唯一键。)

要向users表添加联接,以限制从a返回的行,例如:

SELECT a.id   AS a_id
     , a.info AS a_info
     , b.id   AS b_id
     , b.info AS b_info
  FROM stats a
  JOIN users au ON au.id = a.user_id AND au.city=1
  JOIN stats b ON a.id != b.id 
 LIMIT 25

如果要限制为ab返回的行,请在users表中添加另一个联接:

SELECT a.id   AS a_id
     , a.info AS a_info
     , b.id   AS b_id
     , b.info AS b_info
  FROM stats a
  JOIN users au ON au.id = a.user_id AND au.city=1
  JOIN stats b ON a.id != b.id 
  JOIN users bu ON bu.id = b.user_id AND bu.city=1
 LIMIT 25

这不是实现这一目标的唯一方法。例如,您可以使用a.user_id IN (subquery)EXISTS (subquery)谓词。

(如果您以可读的方式格式化SQL,则SQL更容易使用。)

答案 2 :(得分:1)

这是一种方法:

SELECT a.id as a_id, a.info as a_info, 
       b.id as b_id, b.info as b_info 
FROM stats AS a 
JOIN stats as b
     ON a.id != b.id 
where a.user_id in (select user_id from users where users.city = 1)
LIMIT 25

您也可以将此表达为连接(在MySQL中效率更高):

SELECT a.id as a_id, a.info as a_info, 
       b.id as b_id, b.info as b_info 
FROM stats AS a 
JOIN stats AS b
     ON a.id != b.id 
JOIN users AS u
     ON a.user_id = u.user_id 
     AND u.city_id = 1
LIMIT 25

答案 3 :(得分:1)

好吧,当你在查询中使用表stats两次时,你实际上也需要为users表提供两个连接。 (对于统计数据A和统计数据B)

SELECT a.id as a_id, a.info as a_info, 
       b.id as b_id, b.info as b_info 
FROM stats AS a 
JOIN stats AS b ON a.id != b.id 
JOIN users AS a_users ON a.user_id = a_users.id
JOIN users AS b_users ON b.user_id = b_users.id
WHERE a_users.city = 1 
   OR b_users.city = 1
LIMIT 25