根据另一个表对一个表进行排序
我有一个表 A.
|----+----| | P | S | |----+----| | p1 | 1 | | p2 | 7 | | p3 | 14 | | p4 | 23 | | p5 | 1 | |----+----|
和表 B
|----+----| | S | C | |----+----| | 1 | 21 | | 5 | 21 | | 23 | 21 | | 1 | 30 | | 7 | 90 | |----+----|
我需要对表 A 进行排序。
排序顺序:
A. TableA.S exists where (TableA.S = TableB.S) and TableB.C = 21 B. TableA.P
最终输出:
|----+----| | P | S | |----+----| | p1 | 1 | | p4 | 23 | | p5 | 1 | | p2 | 7 | | p3 | 14 | |----+----|
这需要转换为 DBIx::Class 查询。
我尝试了以下操作:
Select tableA.P, tableA.S from tableA left join tableB on tableA.S = tableB.S where (tableB.C = 21 or tableB.C is NULL) order by tableB.C, tableA.P
但是我缺少某个地方来获取 tableB.S 为“7”的结果。
谢谢。
I have a table A.
|----+----| | P | S | |----+----| | p1 | 1 | | p2 | 7 | | p3 | 14 | | p4 | 23 | | p5 | 1 | |----+----|
and table B
|----+----| | S | C | |----+----| | 1 | 21 | | 5 | 21 | | 23 | 21 | | 1 | 30 | | 7 | 90 | |----+----|
I need to sort table A.
Sorting order:
A. TableA.S exists where (TableA.S = TableB.S) and TableB.C = 21 B. TableA.P
Final Output:
|----+----| | P | S | |----+----| | p1 | 1 | | p4 | 23 | | p5 | 1 | | p2 | 7 | | p3 | 14 | |----+----|
This needs to be converted to DBIx::Class query.
I tried following:
Select tableA.P, tableA.S from tableA left join tableB on tableA.S = tableB.S where (tableB.C = 21 or tableB.C is NULL) order by tableB.C, tableA.P
But I am missing somewhere to get the result where tableB.S is '7'.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于 A 中的所有记录,按
AP
排序,在 B 中找到匹配的记录,然后按AP
对其他记录排序。This sorts by
A.P
for all the records in A a matching record is found in B then byA.P
for the other records.您实际上可以避免使用
CASE
或相关的等效项(例如COALESCE(...)
和特定于数据库的相关函数):为什么这有效? Oracle(和其他一些数据库)的默认行为是将
null
排序为“最大”值(有些人认为它是“最低”值,在这种情况下修复起来很简单)。因此,首先给出在给定列中具有值(这是一个常量值)的行,然后给出那些没有...You can actually avoid the use of
CASE
or related equivalents (such asCOALESCE(...)
and the db-specific related functions):Why does this work? Default behavior of Oracle (and some other dbs) is that
null
sorts as the "greatest" value (some consider it the "lowest" value, which would be trivial to fix in this case). So first rows with a value in the given column (which is a constant value) are given, then those without...