简体   繁体   中英

MySQL - INNER JOIN query with many to many relation

I'm trying to figure out to work with JOIN, however I'm stuck somewhere.

I have two tables:

Post (postid,title) with values (1,'a'), (2,'b'),(3,'c'),(4,'d'),...
Filter (postid,reader) values (1,3),(1,2),(1,6),(1,10),(2,1),...

And I'm trying this query:

SELECT post.title
FROM post
INNER JOIN filter ON filter.reader ='2'
LIMIT 0 , 10

What I want are all the titles from table post where the id (in this case 2) matches the reader in table filter.

The query works but I'm getting duplicates, so I'm missing a crucial point somewhere ?

The reason why you are getting multiple result is because your query produces cartesian product from both tables due because you didn't specify on how the tables should be joined.

SELECT post.title
FROM   post
       INNER JOIN filter 
           ON filter.postID = post.postID // tells how are tables be joined
WHERE  filter.reader = '2'
LIMIT 0 , 10

To further gain more knowledge about joins, kindly visit the link below:

SELECT post.title
FROM post
JOIN filter USING (postid)
WHERE filter.reader ='2'
LIMIT 10

You were joining on the condition that filter.reader = '2' , which is equivalent to having it in the WHERE clause. That means you were performing a cross join (cross product) of all post and filter rows and then filtering those results on filter = '2' , which would result in many posts with a mismatched post ID. You need to add the additional condition that the Post and Filter postids match.

You can also do it like this

"select post.*,filter.* from post, filter where filter.postID=post.postID  and filter.reader='2' limit 0,10"

Hope this helps

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