Kohana:如何将查询括在括号中?
我需要创建像这样的查询(我正在使用 PostgreSQL):
(SELECT * FROM t1 WHERE a>b ORDER BY a DESC)
UNION ALL
(SELECT * FROM t1 WHERE a<b ORDER BY a DESC)
所以,我正在尝试使用查询生成器
$query1 = DB::select('*')
->from('t1')->where('a', '>', 'b')->order_by('a', 'desc');
$query2 = DB::select('*')
->from('t1')->where('a', '<', 'b')->order_by('a', 'desc');
$result = $query1->union($query2, TRUE);
,但结果我有 sql 查询,其中选择不带括号。像这样:
SELECT * FROM t1 WHERE a>b ORDER BY a DESC
UNION ALL
SELECT * FROM t1 WHERE a<b ORDER BY a DESC
并得到 SQL 语法错误...对不起我的英语
I need to create query like (i'm using PostgreSQL):
(SELECT * FROM t1 WHERE a>b ORDER BY a DESC)
UNION ALL
(SELECT * FROM t1 WHERE a<b ORDER BY a DESC)
So, I'm trying to use query builder
$query1 = DB::select('*')
->from('t1')->where('a', '>', 'b')->order_by('a', 'desc');
$query2 = DB::select('*')
->from('t1')->where('a', '<', 'b')->order_by('a', 'desc');
$result = $query1->union($query2, TRUE);
But in result i have sql query where selects without brackets. Like this:
SELECT * FROM t1 WHERE a>b ORDER BY a DESC
UNION ALL
SELECT * FROM t1 WHERE a<b ORDER BY a DESC
And get SQL syntax error... Sorry for my english
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不
SELECT * FROM t1 WHERE a != b ORDER BY a DESC
?编辑
对于更复杂的查询,当你确实需要两个或多个ORDER BY时,我只能看到这个解决方案:
Why not
SELECT * FROM t1 WHERE a != b ORDER BY a DESC
?EDIT
For more complex query, when you really need two or more ORDER BY, I can see only this solution:
解决此问题的另一种方法是修改
class Database_Query_Builder_Select
。这样可以创建带括号的联合查询,例如:(select_1) union (select_2) union (select_n)
。您可以在每个SELECT
语句中使用ORDER BY
和LIMIT
1) 创建文件夹 application/classes/database/query/builder/
2)创建文件select.php
3)将此代码插入到创建的文件中:
}
Another way to solve this problem is modify
class Database_Query_Builder_Select
. This way create unions query with brackets like:(select_1) union (select_2) union (select_n)
. And you can useORDER BY
andLIMIT
in eachSELECT
statement1) Create folder application/classes/database/query/builder/
2) Create file select.php
3) Insert into created file this code:
}