我从3个表中获取记录:
(
SELECT
f.id AS id,
'Faktura VAT' as type,
DATE_FORMAT(f.date_issue, '%d.%m.%Y') AS date_issue
FROM Invoice_vat f
)
UNION ALL
(
SELECT
f.id AS id,
'Faktura korygująca' as type,
DATE_FORMAT(f.date_issue, '%d.%m.%Y') AS date_issue
FROM Invoice_fks f
)
UNION ALL
(
SELECT
f.id AS id,
'Faktura proforma' as type,
DATE_FORMAT(f.date_issue, '%d.%m.%Y') AS date_issue
FROM Invoice_pro f
)
ORDER BY date_issue DESC
我尝试使用字段“date_issue”对此进行排序,但这不起作用......有什么想法吗?
答案 0 :(得分:3)
按“date_issue”排序。问题在于它是一种糟糕的格式,即月中的第一天。因此,列表可能从1月1日开始,但2月1日在1月2日之前开始。我将通过使用规范格式YYYY-MM-DD(日期的ISO标准格式)来解决此问题。
您也可以通过在输出中包含原始列来轻松解决此问题:
(
SELECT
f.id AS id,
'Faktura VAT' as type,
DATE_FORMAT(f.date_issue, '%d.%m.%Y') AS date_issue,
f.date_issue as orig_date_issue
FROM Invoice_vat f
)
UNION ALL
(
SELECT
f.id AS id,
'Faktura korygująca' as type,
DATE_FORMAT(f.date_issue, '%d.%m.%Y') AS date_issue,
f.date_issue as orig_date_issue
FROM Invoice_fks f
)
UNION ALL
(
SELECT
f.id AS id,
'Faktura proforma' as type,
DATE_FORMAT(f.date_issue, '%d.%m.%Y') AS date_issue,
f.date_issue as orig_date_issue
FROM Invoice_pro f
)
ORDER BY orig_date_issue DESC;
如果您实际上不想选择该字段,则可以使用子查询。
答案 1 :(得分:1)
您按照date_issue
的修改版进行排序,因此它将排序为字符串,而不是日期。
尝试对最后的日期进行格式化,而不是针对每个Union
进行格式化:
Select ID,
Type,
DATE_FORMAT(date_issue, '%d.%m.%Y') As Date_Issue
From
(
(
SELECT
f.id AS id,
'Faktura VAT' as type,
f.date_issue
FROM Invoice_vat f
)
UNION ALL
(
SELECT
f.id AS id,
'Faktura korygująca' as type,
f.date_issue
FROM Invoice_fks f
)
UNION ALL
(
SELECT
f.id AS id,
'Faktura proforma' as type,
f.date_issue
FROM Invoice_pro f
)
) A
ORDER BY A.date_issue DESC