等待朋友请求查询朋友表并从其他表中获取数据

时间:2013-11-05 14:28:41

标签: mysql sql join subquery

要获取我使用的所选用户的待处理请求:

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它正确返回用户3. VALUES(3,2,1)

但我希望获得有关此用户3的更多数据。

我需要来自name_surname表的avatarusers。 以及来自word_id表格的此用户的所有connections个作为回报,将根据word显示来自words_en的{​​{1}}。

感谢分配!

P.S。我试过这个:

word_id

2 个答案:

答案 0 :(得分:1)

以下是以下查询的SQL Fiddle,这是我认为你所追求的。

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

答案 1 :(得分:1)

基于这个问题和您之前的问题,我认为您可能正在寻找类似的东西:

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