我有一个令我困惑的MySQL查询。我试图从两个不同的表(模糊和用户)中获取特定信息,同时将其限制为仅关注的人。
我有以下查询:
SELECT DISTINCT blurbs.text, blurbs.timestamp, users.name,
users.username, users.profilepic, users.id
FROM blurbs,users
LEFT OUTER JOIN follows
ON blurbs.uid = follows.following AND follows.follower = ?
WHERE (blurbs.uid = $user_id OR follows.following IS NOT NULL)
AND (LOWER(blurbs.text) LIKE '%$query%' OR LOWER(users.name) LIKE '%$query%')
AND blurbs.is_private=0 AND blurbs.uid=users.id
LIMIT 0,30
它没有正常工作,但由于连接,我变得过于困惑。
我应该怎么做才能解决这个问题?
答案 0 :(得分:1)
尝试通过where子句仅使用所有连接条件,例如
select a.*, b.* //<-- Selectign data from first two tables
from table1 a, table2 b, table1 c
where a.id = b.id //<-- joining condition for first two tables
and a.xxx= c.yyyyy //some relation with third table
and c.aaa =.... //filter conditions using third table
and c.bbb =... //filter conditions using third table
尝试按以下方式对您的查询进行修改:
SELECT DISTINCT blurbs.text, blurbs.timestamp, users.name,
users.username, users.profilepic, users.id
FROM blurbs,users, follows
WHERE blurbs.uid=users.id
AND blurbs.uid = follows.following
AND follows.follower = ?
AND (blurbs.uid = $user_id OR follows.following IS NOT NULL)
AND (LOWER(blurbs.text) LIKE '%$query%' OR LOWER(users.name) LIKE '%$query%')
AND blurbs.is_private=0
LIMIT 0,30
完成此操作后,我希望您能更好地控制/管理所需的过滤条件。
答案 1 :(得分:1)
虽然我不完全确定这是否正是您正在寻找的,但让我根据我对您的问题的理解来解释我的所作所为。 首先,在模糊和用户之间进行INNER JOIN而不是交叉连接,假设有一个用户进行模糊处理 此外,既然你说你只想把它限制在跟随者,我想你可以用INNER JOIN替换LEFT OUTER来帮助过滤掉非跟随者。
SELECT DISTINCT
blurbs.text,
blurbs.timestamp,
users.name,
users.username,
users.profilepic,
users.id
FROM blurbs
INNER JOIN users
ON blurbs.uid = users.id
INNER JOIN follows
ON blurbs.uid = follows.following
AND follows.follower = users.id
WHERE blurbs.uid = $user_id
AND (LOWER(blurbs.text) LIKE '%$query%' OR LOWER(users.name) LIKE '%$query%')
AND blurbs.is_private=0
LIMIT 0,30