简体   繁体   中英

Sorting results of UNION query combining two tables by the table of origin

I'm using the UNION operator to select results from two different tables. I want results from the first table result to come before those from the second table.

For example: I have the tables customer_coupons and segment_coupons. Both tables have a column named coupon_id. When I run a query involving a UNION of these two tables, it returns the correct records, but they are not the order I want: It gives me the coupon_ids of both tables mixed in ascending order, but I want to show ALL coupon_ids of the first table and then ALL coupon_ids of the second table.

Here's the query as it currently exists:

SELECT coupon_id FROM customer_coupons UNION SELECT coupon_id FROM segment_coupons;

How can I change this so that all results from the first half of the query come before all results of the second half?

Put in a fixed table-identifying field:

(SELECT 1 AS source_table, coupon_id
FROM customer_coupons)

UNION ALL

(SELECT 2 AS sourcE_table, coupon_id
FROM segment_coupons)

ORDER BY source_table, coupon_id

Note the brackets around the individual queries. This forces MySQL to apply the order by to the result of the union, not to the 2 sub-query.

SELECT * FROM (
SELECT coupon_id, 1 as myorder
FROM   customer_coupons
UNION
SELECT coupon_id 2 as myorder
FROM   segment_coupons)
Order by myorder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM