一个关于 联合查询union 和排序order by 的例子

其实还有更简单的方法

Title

还可以把个别的select命令用圆括号,这样,可以对每次查询以及最终结果做出limit和order by 设置。

(select * from tbl1 order by colA limit 10) union (select * from tbl2 order by colA limit 10) order by

coltimestamp limit 5






// 查询有效期内的计划任务节点
        string sql 
=  " select      g.grade_name,   "
            
+  "  ''   as  degree_name,"
            
+  "  ''   as  reason, "
            
+  "  ' project_node '   as  node_type, "
            
+  "  ''   as  fact_node_name, "
            
+  " p.create_time, "
            
+  "    p.id,    p.project_id,     p.node_name,        p.deptids,"
            
+  "    p.node_begin_time,         p.node_end_time,    p.worklevel"
            
+  "     from      hrp_project_node p "
            
+  "     left   join  hrp_cycle_grade g  on  g.id  =  p.worklevel "
            
+  "     where  p.state  =   0    and   p.node_state  <>   3  "
            
+  "  and  UNIX_TIMESTAMP(p.node_begin_time)  <  UNIX_TIMESTAMP( ' " + DateTime.Now.ToString() + " ' ) "
            
// 优先查出所有
            
//+  "  and  UNIX_TIMESTAMP(p.node_end_time)  >  UNIX_TIMESTAMP( ' " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ' ) "
            
+  "  and  (p.exeids  like   ' " + userId + "% '   or  p.exeids  like   ' %," + userId + "% ' ) ";

        
// 合并还未执行的任务节点
        sql 
+=  "  union   all  "
            
+  "  select      g.grade_name,   "
            
+  "  ''   as  degree_name,"
            
+  "  ''   as  reason, "
            
+  "  ' fact_node '   as  node_type, "
            
+  "  ''   as  fact_node_name, "
            
+  " f.create_time, "
            
+  "    f.id,    f.project_id,     f.node_name,        f.deptids,"
            
+  "    f.fact_begin_time,         f.fact_end_time,    f.worklevel"
            
+  "     from      hrp_fact_node_execute f "
            
+  "     left   join  hrp_cycle_grade g  on  g.id  =  f.worklevel "
            
+  "     where  f.state  =   0    and   f.fact_state_id  =   0  "
            
+  "  and  (f.exeids  like   ' " + userId + "% '   or  f.exeids  like   ' %," + userId + "% ' ) ";

        sql 
=  string.Format(" select   *   from  ({ 0 })  as  t1   order   by  create_time  desc ", sql);



ps: 我记得这样的一篇帖子好像发表过, 奇怪为什么不找不到了??
当时还参考了别人的博客,
迷糊ing.... 唉, 被 google.com搞得心神不宁啊~~~~

你可能感兴趣的:(order by)