Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql - Mysql : Left join on multiple rows and retrieve 1 row

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
like image 433
Hamid Avatar asked Apr 15 '11 19:04

Hamid


People also ask

Does LEFT join return multiple rows?

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.

WHAT IF LEFT join has multiple matches?

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.

Does LEFT join change number of rows?

condition.

How many rows will return for left join?

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.


1 Answers

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
like image 160
Pascal MARTIN Avatar answered Oct 20 '22 00:10

Pascal MARTIN