从具有不同顺序的表中选择列

问题描述 投票:0回答:1

我有一位同桌顾客。该表包含列

cust_id
member
date
。 cust_id 是主键(自动递增),member 可以是 1 或 0,date 包含时间戳。我想在 MySQL 上运行一个查询,让我选择成员 = 1 的 cust_id 并按日期排序,然后选择成员 = 0 的 cust_id 并按 cust_id 排序。两者都应按降序排列(即从最新或最大到最旧或最小)。我尝试过 UNION 但 SQL 给出错误,因为列日期不存在。

SELECT `cust_id` FROM `customer` WHERE `member` = 1 ORDER BY `date` DESC
SELECT `cust_id` FROM `customer` WHERE `member` = 0 ORDER BY `cust_id` DESC

我想合并这两个查询的结果。 我期待这样的输出:

客户 ID 会员 日期
25 1 2022-05-01 22:22:22
30 1 2021-01-11 05:23:11
50 0 2023-09-01 22:22:22
49 0 2023-08-21 20:20:20
46 0 2023-08-20 19:20:21

但我想我错过了一些东西。

请帮忙。

sql mysql phpmyadmin
1个回答
0
投票

您可以在 MySQL 中使用括号来让它工作

CREATE tABLe customer ( `cust_id` int,`member` int,`date` date)
(SELECT `cust_id`,`member`,`date` FROM `customer` WHERE `member` = 1 ORDER BY `date` DESC)
UNION 
(SELECT `cust_id`,`member`,`date` FROM `customer` WHERE `member` = 0 ORDER BY `cust_id` DESC)
客户 ID 会员 日期

小提琴

© www.soinside.com 2019 - 2024. All rights reserved.