Mysql基于当前用户与搜索用户的友谊状态进行选择

时间:2013-11-12 19:26:58

标签: mysql sql

sql fiddle:http://www.sqlfiddle.com/#!2/60689e/12

此刻查询如下:

SELECT DISTINCT u.name_surname, u.avatar, u.location
FROM users AS u
  JOIN connections AS c ON c.user_id = u.id
  JOIN words_en AS w ON w.id = c.word_id
WHERE (w.word = :kwd
  OR u.location = :kwd
  OR u.name_surname = :kwd)
AND u.privacy > 0
AND c.deleted <> 1

这是一个用户的搜索查询,它会查看位置name_surname和单词,并显示在这些列中任何位置拥有此关键字的用户。

我想以某种方式在此查询中合并当前用户和搜索的用户关系。

u.privacy可以是0,2,3。 0表示私有,在搜索结果中省略。 2只是朋友。每个人都是3。我很难融入这个隐私= 2部分。因此,如果发现用户隐私设置是2,那么我要比较他们的关系,如果他们是朋友显示搜索用户,如果不是不显示他。

关系在朋友表中存储为双向流。

这是我用来选择所有person1的朋友的查询:

SELECT GROUP_CONCAT(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
WHERE f1.status = 1 AND f2.status = 1
  AND f1.asker_user_id = :person1

任何帮助表示赞赏! 谢谢!

更新

SELECT (u.id) as uuid, u.avatar, u.location, u.name_surname,
MAX(CONCAT_WS(", ",
    CASE WHEN w.word = :kwd THEN "words list" END,
    CASE WHEN u.location = :kwd THEN "location" END,
    CASE WHEN u.name_surname = :kwd THEN "name" END)) As matched
FROM users AS u
JOIN connections AS c
  ON c.user_id = u.id
JOIN words_en AS w 
  ON w.id = c.word_id
LEFT JOIN friends AS f1
  ON f1.asker_user_id = :user_id
    AND f1.status = 1
    AND f1.asked_user_id = u.id
WHERE (w.word = :kwd
  OR u.location = :kwd
  OR u.name_surname = :kwd)
AND (u.privacy = 3 OR (u.privacy = 2 and f1.id IS NOT NULL))
AND c.deleted <> 1
GROUP BY u.id
ORDER BY matched DESC

此查询有效,但如果用户在连接中根本没有单词,那么即使匹配在位置中为正,select也不会返回任何内容。

1 个答案:

答案 0 :(得分:0)

您需要在SQLFiddle中加载更好的数据。所有用户的隐私设置为0.此外,一旦您加载数据,让我知道person1和kwd的值需要在您的示例数据中获得结果

更改为不考虑任何字词/连接

SELECT DISTINCT u.name_surname, u.avatar, u.location
FROM users AS u
LEFT JOIN connections AS c
  ON c.user_id = u.id
    AND c.deleted <> 1
LEFT JOIN words_en AS w 
  ON w.id = c.word_id
LEFT JOIN friends AS f1
  ON f1.asker_user_id = :person1
    AND f1.status=1
    AND f1.asked_user_id = u.uid
WHERE (w.word = :kwd
  OR u.location = :kwd
  OR u.name_surname = :kwd)
AND (u.privacy=3 OR (u.privacy=2 and f1.id IS NOT NULL))