I have 2 tables:
Table : Movies
MovieID -- Name
1 -- Movie1
2 -- Movie2
Table: Types
MovieID -- Type
1 -- DVD
1 -- Bluray
1 -- VCD
2 -- DVD
I need a query to find out this in one row: Movie1 : DVD - Bluray - VCD
I used:
SELECT Movies.Name,
IF(TYPE = 'DVD', 1, 0 ) AS DVD,
IF(TYPE = 'Bluray', 1, 0 ) AS Bluray,
IF(TYPE = 'VCD', 1, 0 ) AS VCD
FROM Movies LEFT JOIN Types ON Movies.MovieID = Types.MovieID
But it return multiplate lines:
Movies.Name -- DVD -- Bluray -- VCD
Movie1 -- 1 -- 0 -- 0
Movie1 -- 0 -- 1 -- 0
Movie1 -- 0 -- 0 -- 1
Movie2 -- 1 -- 0 -- 0
I want:
Movie1 -- 1 -- 1 -- 1
Movie2 -- 1 -- 0 -- 0
Introduction to SQL Server LEFT JOIN clause The LEFT JOIN clause allows you to query data from multiple tables. The LEFT JOIN returns all rows from the left table and the matching rows from the right table. If no matching rows are found in the right table, NULL are used.
A left join returns all rows from x, and all columns from x and y. If there are multiple matches between x and y, all match combinations are returned.
condition.
The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.
The group_concat()
function might do the trick, here.
Not tested, but I suppose something like this should work :
SELECT Movies.Name,
group_concat(type separator ' - ') as type
FROM Movies
LEFT JOIN Types ON Movies.MovieID = Types.MovieID
group by Movies.Name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With