Marc El Bichon Marc El Bichon - 4 months ago 6
MySQL Question

Mysql query with multiple LEFT join issue

I want to get this kind of result from a mysql query:


Name | Asked Date | Granted Date | Duration

Joe | 2016-07-01 10:02:01 | 2016-07-01 10:02:05 | 10

Ben | 2016-07-01 10:04:24 | 2016-07-01 10:04:26 | 12

....


Every entries are stored in a table that look like this:

id | action_date | action_type | unique_instance | name
12 | 2016-07-01 10:02:01 | Asked | 6546532161654 | Joe
13 | 2016-07-01 10:02:06 | Granted | 6546532161654 | Joe
14 | 2016-07-01 10:05:12 | Asked | 6546532161654 | Ben
15 | 2016-07-01 10:05:15 | Granted | 6546532161654 | Ben
16 | 2016-07-01 10:06:06 | Finished | 6546532161654 | Joe


I've tried to do this query, but it didn't worked:

Select table.name as Name,
table.action_date as Asked,
g.action_date as Granted,
TIMESTAMPDIFF(SECOND, g.action_date, q.action_date) as Duration
FROM table
LEFT JOIN table g ON table.unique_instance = g.unique_instance AND g.action_type = 'Granted'
LEFT JOIN table q ON table.unique_instance = q.unique_instance AND q.action_type = 'Finished'
WHERE table.action_type = 'Asked'
AND table.unique_instance = '6546532161654'
GROUP BY table.action_date;

Answer

As stated in the comments.

Your design of your database seem incorrect as you are not even making use of your ID. You aren't able to identify which record is unique and related to what, however you can still use the name but it's not unique, since later on in the future you are still going to have records with the same name.

My suggestion would be having action_type and ID as primary key. That way you can always use the same ID and changing the action_type accordingly.

Example (note that you can't have more than 1 record containing this):

  1. ID: 1, action_type: Asked
  2. ID: 1, action_type: Granted
  3. ID: 1, action_type: Finished

In order to debug your code, this query should return just 1 record:

select * from table where unique_instance = '6546532161654' AND action_type = 'Granted' 

But since unique_instance is not unique after all, it is going to grab other unwanted data.

Note: Your query is correct.