Join two tables (with a 1-M relationship) where the second table needs to be ‘flattened’ into one row

select s.id,s.name, max(case when e.course_id = 55 then complete else null end) as c55, max(case when e.course_id = 66 then complete else null end) as c66, max(case when e.course_id = 77 then complete else null end) as c77 from student as s left join enrollment as e on s.id = e.student_id group by s.id @Chris. … Read more

MySql. How to use Self Join

You’re so close! Since you say you’re displaying the country and year from A and limiting by A. Country of Turkey, Turkey is all you’re going to see. You either need to change the selects to be B.country and B.year or change the where clause to be B.country. This is using a cross join which … Read more

Rails: self join scheme with has_and_belongs_to_many?

Here are some resources which may be helpful: RailsCasts episode #163 Self-Referential Association regarding self-referential many-to-many relationships RailsCasts episode #47 Two Many-to-Many. This might be more relevant to what you’re attempting to accomplish A gist someone created for self-referential relationships using HABTM I’ll summarize the information found in those links: Given that you’re describing a … Read more

Explanation of self-joins

You can view self-join as two identical tables. But in normalization, you cannot create two copies of the table so you just simulate having two tables with self-join. Suppose you have two tables: Table emp1 Id Name Boss_id 1 ABC 3 2 DEF 1 3 XYZ 2 Table emp2 Id Name Boss_id 1 ABC 3 … Read more

How to get matching data from another SQL table for two different columns: Inner Join and/or Union?

(The following applies when every row is SQL DISTINCT, and outside SQL code similarly treats NULL like just another value.) Every base table has a statement template, aka predicate, parameterized by column names, by which we put a row in or leave it out. We can use a (standard predicate logic) shorthand for the predicate … Read more