MySQL Forums
Forum List  »  Optimizer & Parser

Re: LEFT JOIN WHERE GROUP BY
Posted by: irek kordirko
Date: April 02, 2012 04:29PM

Use an outer join (left or right) and a case expression,
in this way:

mysql> create table support_internalstatus(
    ->   id int,
    ->   name varchar(20)
    -> );
Query OK, 0 rows affected (0.09 sec)

mysql> insert into support_internalstatus values
    -> ( 1, 'Warranty' ), ( 2, 'Wrong item delivered' ), 
    -> (3, 'Exchanged'), ( 4, 'Warranty expired' );
Query OK, 4 rows affected (0.07 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> create table support(
    ->   statusinternal_id int 
    -> );
Query OK, 0 rows affected (0.09 sec)

mysql> insert into support values 
    -> ( 1 ), ( 1 ), 
    -> ( 2 ), ( 2 ), ( 2 ), ( 2 ),
    -> ( 3 ), ( 3 ), ( 3 ), ( 3 );
Query OK, 10 rows affected (0.06 sec)
Records: 10  Duplicates: 0  Warnings: 0

mysql> SELECT sum( case when s.statusinternal_id  is null then 0 else 1 end ) count, name
    -> FROM support s
    -> RIGHT JOIN support_internalstatus si
    -> ON si.id = s.statusinternal_id
    -> GROUP BY si.id 
    -> ;
+-------+----------------------+
| count | name                 |
+-------+----------------------+
|     2 | Warranty             |
|     4 | Wrong item delivered |
|     4 | Exchanged            |
|     0 | Warranty expired     |
+-------+----------------------+
4 rows in set (0.00 sec)

Options: ReplyQuote


Subject
Views
Written By
Posted
2944
April 02, 2012 02:51AM
1232
April 02, 2012 12:04PM
1274
April 02, 2012 01:24PM
Re: LEFT JOIN WHERE GROUP BY
1288
April 02, 2012 04:29PM
1962
April 03, 2012 12:50AM
1298
April 03, 2012 05:40PM
1390
April 03, 2012 11:22PM
1231
April 04, 2012 05:12PM
1002
April 04, 2012 11:10PM
1509
April 05, 2012 08:01PM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.