艰难的mysql查询,需要用户之间共同的词汇

时间:2013-11-26 16:09:04

标签: mysql sql database

我关注了mysql查询:

SELECT u.name_surname, 
       u.avatar,
       GROUP_CONCAT(DISTINCT w.word ORDER BY w.word ASC) AS asker_words,
       (a.friend_id) AS asker_id
FROM users u
INNER JOIN 
(
SELECT f1.asker_user_id AS friend_id
    FROM friends AS f1 
    LEFT JOIN friends AS f2
        ON f1.asked_user_id = f2.asker_user_id
        AND f1.asker_user_id = f2.asked_user_id   
    WHERE f1.status = 1 AND f2.status IS NULL
    AND f1.asked_user_id = :user_id
) a ON a.friend_id = u.id
LEFT JOIN connections c ON u.id = c.user_id
LEFT JOIN words_en w ON w.id = c.word_id
        WHERE c.invisible <> 1
          AND c.deleted <> 1
GROUP BY 1

它的作用主要是向我提供针对当前用户的朋友请求(ask_user_id)。

Friends table is simple:
id | asker_user_id | asked_user_id | status | created

上面的查询为我提供了与当前用户发起好友请求的用户,以及提问者用户在其帐户下的字词。

我有两个问题,我无法解决。

1)此查询抓取来自提问者用户的所有单词。相反,我想抓住提问者的话,并且要求共同/相同的减号设置为不可见或删除。

2)即使用户没有共同的单词,朋友请求查询也应该抓住行。 Atm,当提问者用户在他的帐户请求下没有任何文字消失时。

3)按照共同的词数排序。

SQLfiddle:http://www.sqlfiddle.com/#!2/b158f/1

请注意结果中,word1 word2是共同的,但欢迎并不常见。

1 个答案:

答案 0 :(得分:0)

我不明白你的第二个问题陈述。你能举一个关于这个数据的SQLfiddle的例子吗?否则,请参阅此http://www.sqlfiddle.com/#!2/13979/17。在新的LEFT JOIN子句中,硬编码1应与INNER JOIN子句中的1相同。:

SELECT u.name_surname, 
       u.avatar,
       GROUP_CONCAT(DISTINCT w.word ORDER BY w.word ASC) AS asker_words,
       (a.friend_id) AS asker_id
       ,COUNT(w.id) AS WordCount
FROM users u
INNER JOIN 
(
SELECT f1.asker_user_id AS friend_id
    FROM friends AS f1 
    LEFT JOIN friends AS f2
        ON f1.asked_user_id = f2.asker_user_id
        AND f1.asker_user_id = f2.asked_user_id   
    WHERE f1.status = 1 AND f2.status IS NULL
    AND f1.asked_user_id = 1
) a ON a.friend_id = u.id
LEFT JOIN connections c 
  ON u.id = c.user_id
    AND c.invisible <> 1
    AND c.deleted <> 1
LEFT JOIN connections c2
  ON c2.word_id = c.word_id
    AND c2.user_id = 1
    AND c2.invisible <> 1
    AND c2.deleted <> 1
LEFT JOIN words_en w 
  ON w.id = c2.word_id
GROUP BY u.name_surname
ORDER BY WordCount DESC;