使用ORDER BY组织结果

时间:2013-03-22 15:14:42

标签: mysql

现在我正在使用看起来像这样的SQL查询。

SELECT 
'Name',
'Department' 
UNION ALL tb1.Name, 
tb2.Department FROM tb1 
LEFT OUTER JOIN tb2 ON 
tb1.MyIndex = tb2.MyIndex 
ORDER BY Name, Department ASC;

我所面临的困境是,排序并没有真正按照我需要的方式运作。为了导出起见,我需要将标题保留在查询的顶部,而且我的部门也没有正确排序。我的输出看起来像这样。

David   |    1
Joe     |    1
Phil    |    3
George  |    2
Name    | Department

现在当我拿出标题时,我可以按列排序

SELECT tb1.Name, tb2.Department
FROM tb1 LEFT OUTER JOIN tb2 ON
tb1.MyIndex = tb2.MyIndex
ORDER BY tb1.Name, tb2.Department

我的输出看起来不错。

David   |    1
Joe     |    1
George  |    2
Phil    |    3

除了一件事,此查询以

结束
INTO OUTFILE 'file.txt' FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '' LINES
TERMINATED BY '\n'

当我导入这个文件时,我需要标题,但是当我把标题放入时我必须搜索标题而不是列名,而ORDER BY甚至不能正常工作,所以我的问题是如何我是否订购了

ORDER BY tb1.Name, tb2.Department 

这样我的结果看起来就像我的第二组结果在这篇文章中但是包含了标题?

2 个答案:

答案 0 :(得分:2)

要正确执行此操作,您不应该依赖联合输出的顺序。相反,要明确:

select name, department
from (SELECT 'Name' as name, 'Department' as department, 1 as isheader
      UNION ALL
      SELECT tb1.Name, tb2.Department, 0 as isheader
      FROM tb1 LEFT OUTER JOIN tb2
           ON tb1.MyIndex = tb2.MyIndex
     ) t
ORDER BY isheader desc, tb1.Name, tb2.Department+0

为了清楚起见,documentation说:

  

但是,对单个SELECT语句使用ORDER BY意味着   没有关于行在最终结果中出现的顺序   因为UNION默认生成一组无序行。

答案 1 :(得分:1)

您应该可以使用子查询执行此操作:

SELECT 
  'Name' as header1,
  'Department' as header2 
UNION ALL 
select 
  suq_query.Name,
  suq_query.Department
from
(
  select tb1.Name, 
    tb2.Department 
  FROM tb1 LEFT OUTER JOIN tb2 ON tb1.MyIndex = tb2.MyIndex 
  ORDER BY Name ASC, Department ASC
) as suq_query
INTO OUTFILE 'file.txt' 
FIELDS TERMINATED BY '|' 
OPTIONALLY ENCLOSED BY '' LINES
TERMINATED BY '\n';