0

在一个教程中,我看到了这个 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。我尝试从表中获取所有用户statsusers.city=1例如),但我仍然找不到方法,如何实现...

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

我会感谢每一个建议,谢谢

4

4 回答 4

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 中的每一行都与 stats 中的每一行匹配,除了匹配自身。(假设这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 格式化为可读的格式,那么它的使用会容易得多。)

于 2012-08-30T21:26:34.680 回答
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
于 2012-08-30T21:26:34.693 回答
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
于 2012-08-30T21:26:34.747 回答
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
于 2012-08-30T21:25:15.257 回答