Try this
SELECT sw.word
FROM words w
INNER JOIN
synonyms s ON
s.w_id = w.id
INNER JOIN
words sw ON
sw.id = s.s_id
WHERE w.word = 'Profit'
You may also replace the 'Profit' by a variable and make this a function.
Вопрос
I try to make SQL queries but i can't do it right. I have one DB with 2 tables.The first table contains the ID and the words, and the second contains the ID and synonyms. I need to make three queries to the database to get the synonyms of one word entered, but the problem in the last query (as I consider). I even have instructions on how to create these questions correctly, but I'm stuck:
To start getting the words id query
SELECT id FROM words WHERE word = 'Profit'
. After that, we get a list of synonyms
SELECT w_id, s_id FROM synonyms WHERE w_id = '1234 'or s_id = '1234'.
Sort duplicate values and pick synonyms
SELECT word FROM words WHERE id IN (1,2,3,4,5 ...)
I think that instead of 1,2,3,4,5 must be previous query, but if I use it, the output is not given me anything or gives not what I need (ID instead of synonyms)
Data from table words: (1,'word1'),(2,'word2'),(3,'word3'),(4,'word4'),(5,'word5'),(6,'word6'),(7,'word7'),(8,'word8'), (9,'word9'),(10,'word10')
and from table synonyms: (1,2),(1,3),(1,4),(1,5),(1,6),(1,7),(1,8),(1,9),(1,10)
For example: If I write the word "word1"then the last query must find me all the synonyms related to it from the second table and display the result on the screen, but instead gives me the same word
Решение
Try this
SELECT sw.word
FROM words w
INNER JOIN
synonyms s ON
s.w_id = w.id
INNER JOIN
words sw ON
sw.id = s.s_id
WHERE w.word = 'Profit'
You may also replace the 'Profit' by a variable and make this a function.
Другие советы
You must handle both directions; w_id
→ s_id
, and s_id
→ w_id
.
There are several possible implementations; one is this:
SELECT word
FROM words
WHERE id IN (SELECT s_id
FROM synonyms
WHERE w_id = (SELECT id
FROM words
WHERE word = 'Profit'))
OR id IN (SELECT w_id
FROM synonyms
WHERE s_id = (SELECT id
FROM words
WHERE word = 'Profit'))