0

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

Query at the moment looks like this:

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

It is a search query for user, that looks into location name_surname and words and shows user that owns this keyword anywhere in those columns.

I would like to incorporate current user and searched user relationship in this query somehow.

u.privacy can be 0,2,3. 0 means private and is omitted from search results. 2 is friends only. And 3 is everybody. I'm having hard time incorporate this privacy = 2 part. So if found users privacy setting is 2, than I've to compare their relationship and if they are friends show searched user, if not don't display him.

Relationship is stored as a two way stream, in friends table.

This is query I use to select all person1's friends:

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

Any help appreciated! thanks!

UPDATE

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

This query works, but if user has no word at all in connections, than even if match is positive in location select returns nothing.

4

1 回答 1

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))
于 2013-11-13T00:59:33.307 回答