简体   繁体   中英

SQL: query repeating rows in join

I'm trying to display all my exercises which are in course A (course_id '1')

When I run this query:

SELECT * FROM exercises 
LEFT JOIN sessions on sessions.session_id 
WHERE course_id ='1'

I get this:

询问

It's worth noting that courses have sessions and in that session there are these exercises. Realistically only exercise_id's 1 and 4 are linked to course 1. So why are their duplicate rows being returned? Session_id's 10, 11, 12 and 13 are all part of course 1 but do not have any exercises in them at present. Any help would be appreciated.

The culprit is this line:

LEFT JOIN sessions on sessions.session_id

You're not joining against a column in the other table. Without knowing your schema, I might guess it's exercises.session_id you might need to join on?

Your in condition of the join is missing the condition.

Try something like

SELECT * FROM exercises LEFT JOIN sessions on exercises.session_id = sessions.session_id WHERE course_id ='1' .

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