Show all of the accounting events that took place this year, including any paid invoices (
Figure 10.27).

(SELECT DATE_FORMAT(expense_date, '%Y-%m-%d')
AS dates FROM expenses
WHERE YEAR(expense_date) = YEAR(CURDATE()))
UNION
(SELECT DATE_FORMAT(invoice_date, '%Y-%m-%d')
FROM invoices
WHERE YEAR(invoice_date) = YEAR(CURDATE()))
UNION
(SELECT
DATE_FORMAT(date_invoice_paid, '%Y-%m-%d')
FROM invoices
WHERE YEAR(date_invoice_paid) = YEAR(CURDATE()))
ORDER BY dates ASC;
UNIONs, like
JOINs, can involve multiple queries and tables. In other words, you can
UNION two or more query results. To do so, you just continue on with the
UNION syntax
(SELECTquery UNION SELECTquery2 UNION SELECTquery3).
Each
SELECT query differs from the other ones in two ways. First, I've changed the formatting of the date so that I can sort it better. If I sorted the dates as they were formatted before, they would be sorted alphabetically, not chronologically. Second, each query uses a
WHERE clause to restrict the returned results to only those that took place in the current year.
Finally, all of the results are ordered by the formatted date. Parentheses are used to clarify each query and to make clear that the
ORDER BY applies to the whole
UNION.