I have the following query that I need to convert to rails like syntax. Is there any way to do it or is it better to just use plain MYSQL for this?
SELECT `terminals`.`serial`, Count(*) AS count, MAX(`logs`.`created_at`) AS created_at
FROM
(SELECT * FROM `terminals` WHERE `terminals`.`user_id`= 1) AS terminals
INNER JOIN `bap-backend`.`logs` ON terminals.`serial`=`logs`.`serial`
GROUP BY `serial` ORDER BY `logs`.`created_at`
The inner Select is to make sure only terminals of the current_user get selected, then I only need the terminals serial. I need this query to give an overview of all the user his terminals and display how many logs the terminal has provided and when the last log occured. The query works on my test data only the implementation in rails is a bit complicated for me.
Thanks!
EDIT
For the google people, just use find_by_sql, you can still add variables in it. Just add a class before the command, like following example:
@items_event = Item.find_by_sql(["SELECT items.*, ei_relationships.itemprice, ei_relationships.currency, ei_relationships.itemunit
FROM `ei_relationships` INNER JOIN `items` ON `items`.`id` = `ei_relationships`.`item_id`
WHERE `ei_relationships`.`event_id` = ?", @event[:id]])
I don’t claim to know anything about rails, so I can’t answer that part of the question. But if you do stick with plain MySQL, your query could be cleaned up a little:
This takes out one subquery, which should help your performance.