【问题标题】:Selecting individual values from two tables while getting condition from a third从两个表中选择单个值,同时从第三个表中获取条件
【发布时间】:2012-10-12 22:29:08
【问题描述】:

我有一个令我困惑的 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

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

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

【问题讨论】:

  • 首先,只使用旧的连接样式(带逗号)或JOIN,不能同时使用。并展示一些示例数据和您期望的结果。

标签: mysql join conditional-statements


【解决方案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

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

【讨论】:

    【解决方案2】:

    虽然我不完全确定这是否正是您正在寻找的,但让我根据对您问题的理解来解释我所做的事情。 首先,假设会有一个用户用于一个简介,而不是你的交叉连接,而是在简介和用户之间进行 INNER JOIN 另外,既然您说您只想将其限制为关注者,我认为您可以将 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      • 2019-08-09
      • 1970-01-01
      • 2017-11-20
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多