Pending friend request query for friends table and grabbing data from other tables

為{幸葍}努か 提交于 2019-12-11 03:37:19

问题


To get pending request for selected user I use:

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 = 2

http://www.sqlfiddle.com/#!2/0f7a0d5/65 It correctly returns user 3. VALUES (3,2,1)

But I'd like to get more data about this user 3.

I need name_surname and avatar from users table. And all word_ids of this user from connections table, which in return would show word from words_en based on word_id.

Thanks allot!

p.s. I tried this:

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 
  LEFT 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
  WHERE f1.status = 1 AND f2.status IS NULL
       AND f1.asker_user_id = 2
) 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;

回答1:


Based on this question and your previous questions, i think you might be looking for something like this:

SELECT u.name_surname, 
       u.avatar,
       GROUP_CONCAT(DISTINCT w.word Order by w.word asc) AS words
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 = 2
) 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
GROUP BY u.id;

sqlfiddle demo




回答2:


HERE IS THE SQL Fiddle of the below query, which is what i think you are after.

SELECT users.name_surname, users.avatar,
GROUP_CONCAT(DISTINCT words_en.word Order by words_en.word asc) AS words
FROM 
(
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 = 2
) AS MainQ
INNER JOIN users ON MainQ.friend_id = users.id
INNER JOIN connections ON users.id = connections.user_id
INNER JOIN words_en ON words_en.id = connections.word_id


来源:https://stackoverflow.com/questions/19791301/pending-friend-request-query-for-friends-table-and-grabbing-data-from-other-tabl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!