我有一种情况需要
我有两张表objects
和object_versions
每个对象可以有多个版本,两个表通过
链接 objects.id = object_versions.id
我的订单逻辑是以下abs(object_versions.size - $someNumber)
这非常适合订购问题而没有组我仍然可以在结果中获得所有其他版本。查看方案和小提琴http://www.sqlfiddle.com/#!2/a967b/23
查询1(正确的结果,但没有分组)
SQL
SELECT
objects.id as object_id,
object_versions.id as object_versions_id,
object_versions.size as object_versions_size
FROM objects
INNER JOIN object_versions ON objects.id = object_versions.id
ORDER BY abs(object_versions.size - 1000) ASC;
口才
Object::join('object_versions', 'objects.id', '=', 'object_versions.id')
->orderByRaw("abs(width - ?) ASC", [1000])
->select('objects.id as object_id', 'object_versions.id as object_versions_id', 'object_versions.size as object_versions_size')->get();
结果
id id size
1 1 800
2 2 800
2 2 400
1 1 400
2 2 300
1 1 300
查询2(订单前分组产生的结果不佳)
SQL
SELECT
objects.id as object_id,
object_versions.id as object_versions_id,
object_versions.size as object_versions_size
FROM objects
INNER JOIN object_versions ON objects.id = object_versions.id
GROUP BY object_id
ORDER BY abs(object_versions.size - 1000) ASC;
口才
Object::join('object_versions', 'objects.id', '=', 'object_versions.id')
->orderByRaw("abs(width - ?) ASC", [1000])
->groupBy("objects.id")
->select('objects.id as object_id', 'object_versions.id as object_versions_id', 'object_versions.size as object_versions_size')->get();
结果
id id size
1 1 300
2 2 300
查询3(订单后的分组更正结果,但不知道如何以雄辩的方式生成此内容)
SQL
SELECT * FROM (
SELECT
objects.id as object_id,
object_versions.id as object_versions_id,
object_versions.size as object_versions_size
FROM objects
INNER JOIN object_versions ON objects.id = object_versions.id
ORDER BY abs(object_versions.size - 1000) ASC
) as result
GROUP BY object_id;
口才 我不知道该怎么做......
结果
1 1 800
2 2 800