由于您的数据结构如此复杂,使用 ActiveRecord 对象检索所有内容将变得非常慢非常快(最近遇到了这个问题)。
让我们看看我们能一起解决什么问题。
由于您没有提供 MySQL 问题的示例数据,我自己填写了,但请随时改进数据,我们可能会找到更好的解决方案。
架构
CREATE TABLE IF NOT EXISTS `users` (
`id` int(6) unsigned NOT NULL,
`username` varchar(200) NOT NULL,
`longitude` varchar(200) NOT NULL,
`latitude` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `customers` (
`id` int(6) unsigned NOT NULL,
`user_id` int(6) unsigned NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `products` (
`id` int(6) unsigned NOT NULL,
`customer_id` int(6) unsigned NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `stocks` (
`id` int(6) unsigned NOT NULL,
`product_id` int(6) unsigned NOT NULL,
`quantity` int(200) unsigned NOT NULL,
`updated_at` DATETIME,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `users` (`id`, `username`, `longitude`, `latitude`) VALUES
(1, 'username1', '11.12', '22.33'),
(2, 'username2', '11.12', '22.33'),
(3, 'username3', '11.12', '22.33');
INSERT INTO `customers` (`id`, `user_id`) VALUES
(9, 1),
(10, 2),
(11, 3);
INSERT INTO `products` (`id`, `customer_id`) VALUES
(33, 9),
(34, 10),
(35, 11);
INSERT INTO `stocks` (`id`, `product_id`, `quantity`, `updated_at`) VALUES
(1, 33, 12, '2017-07-17 13:24:01'),
(2, 34, 1, '2017-07-17 13:24:02'),
(3, 35, 99, '2017-07-17 13:24:03'),
(4, 36, 3, '2017-07-17 13:31:01');
查询
SELECT users.id, username, longitude, latitude, products.id as product_id, quantity from `users`
INNER JOIN customers ON user_id = users.id
INNER JOIN products ON customer_id = customers.id
INNER JOIN stocks ON product_id = products.id
ORDER BY stocks.updated_at DESC
结果
id username longitude latitude product_id quantity
1 username1 11.12 22.33 33 12
2 username2 11.12 22.33 34 1
3 username3 11.12 22.33 35 99
对于 Rails 部分,您可以使用如下内容:
data = Users.select("id, longitude etc").
joins(
"INNER JOIN customers ON user_id = users.id etc "
)
SQL Fiddle link