简体   繁体   中英

How do I search for term in separate mysql tables?

I'd like to search multiple columns and multiple tables.

I imported all my tables into sqlfiddle here: http://www.sqlfiddle.com/#!2/60689e/3

What I'd like to select is user id, name_surname, avatar, from users table Based on keyword, matching column "location" or "name_surname" in users table. This is relatively simple:

SELECT u.name_surname,
       u.avatar,
       u.location
FROM users u
WHERE u.location LIKE :kwd
OR u.name_surname LIKE :kwd

The tricky part for me is querying table for matches in words_en table, which essentially should be queried against connections table where I actually can see which user is associated with which word... How do I do this last part escapes me.

So I probably need to:

  1. query words_en and find out if there is a match at all.
  2. if there is a match I need to look at id of word_en word and see if this id exists in connections table.
  3. Select distinct user_ids from connections table.
  4. Select name_surname for the selected user_ids.

Thanks for looking. S.

To get all users based on a search of the words_en table would look something like SQL Fiddle :

SELECT u.id, u.name_surname, u.avatar
FROM users AS u
WHERE u.id IN 
(
  SELECT c.user_id
  FROM connections AS c 
    JOIN words_en AS w 
    ON w.id = c.word_id
  WHERE w.word = 'word1'
    OR w.word = 'word2'
) 
AND u.location LIKE '%Nunya%'
  OR u.name_surname LIKE '%sandro%'

If you want to use the same search term for any of the three fields then use the following:

SELECT 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 LIKE '%word1%'
  OR u.location LIKE '%word1%'
  OR u.name_surname LIKE '%word1%') 
  AND u.privacy = 3

I hope I did not misunderstand your problem. Correct me if I am wrong some where.

SELECT u.name_surname,
       u.avatar,
       u.location
FROM USERS AS U
INNER JOIN CONNECTIONS AS C
ON  C.USER_ID = U.ID
INNER JOIN WORDS_EN AS W
ON  W.ID = C.WORD_ID
AND W.WORD LIKE 'word1%'

I have hard coded word1 for example, you can also make INNER JOIN of WORDS_EN as LEFT JOIN if you need all user information's having connections regardless of their words in WORDS_EN.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM