I am trying to
type
's objects (Published
and InReviewing
from the same model Events
, Published
and Created
, So that I can return an array with a date, and a medium time difference between any of the types InReviewing
and Published
that share a target_id
from each day. I think SQL would return seconds?
Example :
[[Mon, 03 Dec 2012, 110000], [Thu, 13 Dec 2012, 2200000]]
My raw SQL syntax is lacking some conclusions. This is what I have so far :
SELECT target_id, DATE(created_at), COUNT(*)
FROM ( SELECT target_id, DATE(created_at)
FROM events
WHERE created_at > '#{@start_time}'
AND events.type = 'InReviewing'
UNION ALL
SELECT target_id, DATE(created_at)
FROM events
WHERE created_at > '#{@start_time}'
AND events.type = 'Published'
) tmp
GROUP BY DATE(created_at)
Don't mind the #{@start_time
}`, that's using native code to implement a Time here, and it works properly..
Thanks!
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `events` ADD INDEX `events_idx_type_created_at` (`type`,`created_at`);
SELECT
tmp.target_id,
DATE(tmp.created_at),
COUNT(*)
FROM
(SELECT
events.target_id,
DATE(events.created_at)
FROM
events
WHERE
events.created_at > '#{@start_time}'
AND events.type = 'InReviewing'
UNION
ALL SELECT
events.target_id,
DATE(events.created_at)
FROM
events
WHERE
events.created_at > '#{@start_time}'
AND events.type = 'Published'
) tmp
GROUP BY
tmp.date_created_at
ORDER BY
NULL