2

我有一个令我困惑的 MySQL 查询。我试图从两个不同的表(blurbs 和 users)中获取特定的信息,同时将其限制为仅关注的人。

我有以下查询:

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

它工作不正常,但由于连接,我变得过于困惑。

我应该怎么做才能解决这个问题?

4

2 回答 2

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

完成此操作后,我希望您可以更好地控制/管理所需的过滤条件。

于 2012-10-23T02:58:48.763 回答
1

虽然我不完全确定这是否正是您要寻找的,但让我根据对您问题的理解来解释我所做的事情。首先,假设会有一个用户用于一个简介,而不是你的交叉连接,而是你的交叉连接,因为你说你只想将它限制为那些关注的人,我认为你可以替换 LEFT OUTER 带有 INNER JOIN 以帮助过滤掉非关注者。

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
于 2012-10-23T02:59:42.480 回答