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

xienkqul  于 2023-10-20  发布在  PHP
关注(0)|答案(2)|浏览(141)

我有个客人。该表具有列cust_idmemberdate。cust_id是一个主键(自动递增),member可以是1或0,date包含时间戳。我想在MySQL上运行一个查询,它让我选择cust_id,member = 1,order by date,然后选择cust_id,member = 0,order by 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|
但我觉得我漏掉了什么。
请帮帮忙。

pbpqsu0x

pbpqsu0x1#

你可以在MySQL中使用parthesis来让它工作

CREATE tABLe customer ( `cust_id` int,`member` int,`date` datetime)
INSERT INTO customer
    (`cust_id`, `member`, `date`)
VALUES
    (25, 1, '2022-05-01 22:22:22'),
    (30, 1, '2021-01-11 05:23:11'),
      (31, 1, '2022-05-01 21:22:22'),
    (32, 1, '2021-01-11 06: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'),
      (50, 0, '2023-09-01 22:22:22'),
    (51, 0, '2023-08-21 20:20:20'),
    (52, 0, '2023-08-20 19:20:21')
;
Records: 10  Duplicates: 0  Warnings: 0
(SELECT `cust_id`,`member`,`date` FROM `customer` WHERE `member` = 1 ORDER BY `date` DESC LIMIT 10000000)
UNION 
(SELECT `cust_id`,`member`,`date` FROM `customer` WHERE `member` = 0 ORDER BY `cust_id` DESC  LIMIT 10000000)

| 客户ID|构件|日期|
| --|--|--|
| 25 | 1 |2022-05-01 22:22:22|
| 31 | 1 |2022-05-01 21:22:22|
| 32 | 1 |2021-01-11 06:23:11|
| 30 | 1 |2021-01-11 05:23:11|
| 52 | 0 |2023-08-20 19:20:21|
| 51 | 0 |2023-08-21 20:20:20|
| 50 | 0 |2023-09-01 22:22:22|
| 49 | 0 |2023-08-21 20:20:20|
| 46 | 0 |2023-08-20 19:20:21|
fiddle

amrnrhlw

amrnrhlw2#

选择所有并按成员和日期排序:

SELECT cust_id FROM customer ORDER BY member DESC, date DESC

相关问题