Question

I'm aware there are many question already started for SQL n:n queries. However I could'nt find a solution for my problem.

I would like to create a project which is something like a personal thesaurus. In it, the user can define which word is related to other words. I have two tables:

words:
+----+-----------+
| id | word      |
+----+-----------+
|  1 | house     |
|  2 | residence |
+----+-----------+

words_2_words (junction table)
+----+-------+-------+
| id | word1 | word2 |
+----+-------+-------+
|  1 |     1 |     2 |
+----+-------+-------+

Finding all synonyms for house is fairly easy:

SELECT * FROM words_2_words WHERE word1 = 1;

However, to make sure, I also find words which are only listed in column "word2" I actually need 2 queries:

SELECT *, word2 AS synonym FROM words_2_words WHERE word1 = 1;
SELECT *, word1 AS synonym FROM words_2_words WHERE word2 = 1;

How can I put these 2 queries in one query for faster results?

Was it helpful?

Solution

You could use IN:

SELECT CASE WHEN Word1 = 1 THEN Word2 ELSE Word1 END AS Word
FROM words_2_words
WHERE 1 IN (Word1, Word2):

Or UNION:

SELECT Word2 AS Word
FROM words_2_words
WHERE Word1 = 1
UNION [ALL]
SELECT Word1
FROM words_2_words
WHERE Word2 = 1;

Add or remove [ALL] depending on whether you want distinct results or not.


To get the actual word back I would recommend just joining twice, then you can get both words out:

SELECT CASE WHEN w2w.Word1 = $id THEN w2.Word ELSE w1.Word END AS Word
FROM    words_2_words w2w
        INNER JOIN words w1
            ON w2w.word1 = w1.id
        INNER JOIN words w2
            ON w2w.word2 = w2.id
WHERE   $id IN (w2w.Word1, w2w.Word2):

If you really don't want to do this you can just use the same case statement in the join:

SELECT  w.Word
FROM    words_2_words w2w
        INNER JOIN words w
            ON CASE WHEN w2w.Word1 = $id THEN w2w.Word2 ELSE w2w.Word1 END = w.id
WHERE   $id IN (w2w.Word1, w2w.Word2):

OTHER TIPS

If I understand what you're saying correctly, you would just run:

select * from words_2_words where word1 = 1 or word2 = 1

Although you combine 2 queries using a union, that doesn't seem like it's what you actually need to do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top