#Help need in writing a SQL Query

15 messages · Page 1 of 1 (latest)

modern nacelle
#

So I have this join table for two tables ideas and tags.
I want to write a query which lets me find let's say all ideas with having tag_id in [4, 5].

How can I do that ?

I was trying to do this via gorm.io

tired flower
#

you don't need a join for this query, you should only join a table if you need data from both tables, instead you shoud use subquery SQL SELECT DISTINCT * FROM ideas WHERE id IN (SELECT idea_id FROM idea_tags WHERE tag_id IN (4,5));

modern nacelle
#

Hey thank you! but can you show me how can I do this query using Gorm.io ??

visual swan
#

don't use a subquery for this btw, it is probably slower than doing a simple join

modern nacelle
#

@visual swan I did try to do this like this:

SELECT * FROM ideas, idea_tags WHERE ideas.id = idea_tags.idea_id AND tag_id in (4, 5);
#

But then it gives me duplicated rows 🥲

#

This query returns me two rows when in fact it should have returned only one

visual swan
#

that is a cross join

#

select * from ideas left join idea_tags on idea_tags.idea_id = idea.id where tag.id in (4,5)

modern nacelle
visual swan
#

Not familiar with gorm. You have to setup your model objects and relations correctly

hard elbow
#

how is your model looks like?

modern nacelle