我有以下使用 UNION
和 priority
别名列的查询:
SELECT id, name, 4 as priority FROM `topics`
WHERE id IN(17, 18, 19, 20, 21) AND name LIKE 'ge'
UNION
SELECT id, name, 3 as priority FROM `topics`
WHERE id IN(17, 18, 19, 20, 21) AND name LIKE '%ge%'
UNION
SELECT id, name, 2 as priority FROM `topics`
WHERE name LIKE 'ge%'
UNION
SELECT id, name, 1 as priority FROM `topics`
WHERE name LIKE '%ge%'
ORDER BY priority DESC
是否可以将其“翻译”为 Laravel 的查询构建器,使其保留为一个查询?
我知道我可以将所有 SELECT
放在单独的变量中,然后将它们与 ->union()
链接起来,但恐怕这将首先执行 4 个查询,一个一个,最后只是合并结果。
最佳答案
在 Laravel 文档中:
The query builder also provides a quick way to "union" two queries together:
$first = DB::table('users')->whereNull('first_name');
$users = DB::table('users')->whereNull('last_name')->union($first)->get(); The unionAll method is also available, and has the same method signature as union.
我认为,就目前而言,这是在 Laravel 中联合的唯一途径。我认为第一个查询没有获取数据,因为没有添加 ->get() 链。
关于php - Laravel:使用 UNION 的多个 SELECT - 作为一个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28584749/