1

我如何将这两者结合起来?

这个查询:

SELECT f1.asked_user_id AS friend_id
    FROM friends AS f1 JOIN friends AS f2
    ON f1.asked_user_id = f2.asker_user_id
    AND f1.asker_user_id = f2.asked_user_id
    AND f1.asker_user_id = :user_id
WHERE f1.status = 1 AND f2.status = 1

和:

(SELECT GROUP_CONCAT(words_en.word) FROM connections JOIN words_en ON connections.word_id = words_en.id WHERE connections.user_id = friends.friend_id) As friend_words

再做一次加入:

JOIN users ON friends.friend_id = users.id

我在这里尝试了几件事:http ://www.sqlfiddle.com/#!2/85d6d/36

第一个查询从表中选择两种方式的朋友。我从那个查询中得到了friend_id。现在我想更多地了解这个friend_id。所以我想用这个 id 做另一个查询,显示该用户从连接表中的所有 word_ids,word_ids 可用于从 word_en 中获取实际单词。最后,我想从 users 表中获取用户 name_surname。

4

1 回答 1

1

尝试这个:

SELECT a.name_surname,GROUP_CONCAT(Distinct w.word Order by w.word asc) AS words
FROM (
  SELECT f1.asked_user_id AS friend_id,
       f1.created,
       u.name_surname,
       u.avatar
  FROM friends AS f1 
  INNER JOIN friends AS f2 ON f1.asked_user_id = f2.asker_user_id
  INNER JOIN users AS u ON f1.asked_user_id = u.id
       AND f1.asker_user_id = f2.asked_user_id
       AND f1.asker_user_id = 1
  WHERE f1.status = 1 AND f2.status = 1
) a
LEFT JOIN connections c ON c.user_id = a.friend_id 
LEFT JOIN words_en w ON c.word_id = w.id
GROUP BY 1;

sqlfiddle demo

有了您的原始查询,我所做的就是将该查询视为表(a)并将LEFT JOIN其与connections表一起处理。然后,LEFT JOINconnectionswords_en表来达到想要的单词。这使得可以获取从原始查询返回的所有用户,即使没有连接/单词。

于 2013-11-04T21:34:31.620 回答