选择余额大于10000且有效期从今天起不到2天的行

时间:2017-04-20 22:05:57

标签: mysql date intervals

我有下表:

[ID] [所有者] [余额] [CreationDate] [ExpirationDate]

到目前为止,代码如下。

CREATE TABLE Account(ID INTEGER PRIMARY KEY AUTOINCREMENT,
                         Owner varchar(50),
                         Balance decimal(7,3),
                         CreationDate timestamp DEFAULT CURRENT_TIMESTAMP,
                         ExpirationDate timestamp DATETIME NOT NULL DEFAULT CURDATE)

    INSERT INTO Account(Owner, Balance, ExpirationDate)
                Values('Jean Claude Van Damme', 6453, '2023-10-06'),
                ('Peter Paul Rubens', 9999, '2018-06-04'),
                ('Rembrandt Harmenszoon van Rijn', 765549, '2023-10-22'),
                ('Pablo Ruiz y Picasso', 972825, '2019-06-13'),
                ('Michelangelo di Lodovico Buonarroti', 7981, '2022-10-27'),
                ('Raffaello Sanzio da Urbino', 548765, '2018-11-17'),
                ('John Doe', 666745, '2021-12-05'),
                ('Mickey Mouse', 10005, '2020-10-21'),
                ('Vincent Willem van Gogh', 453906, '2021-07-13'),
                ('Oliver Hardy', 1005, '2019-01-26')


    SELECT * FROM Account

    SELECT Owner FROM Account WHERE Balance < 10000

首先我不知道'ExpirationDate timestamp DATETIME NOT NULL DEFAULT GETDATE'是否遵守有关日期格式的mysql语法。是yyyy / mm / dd还是mm / dd / yyyy?我知道日期可以转换为尊重欧洲标准,但这对我不感兴趣。

二。我必须“选择余额大于1000且有效期从今天开始不到2天的行。

显然,我会采取简单的方法并添加到我的代码

SELECT Owner FROM Account
WHERE Balance >= 10000 AND ExpirationDate BETWEEN '2017-04-20' AND '2017-04-22'

BUT

我希望从CURRENT_DATE计算日期,无论何时,如

SELECT Owner FROM Account
WHERE Balance >= 10000 AND ExpirationDate BETWEEN CURDATE() AND INTERVAL 2 DAY)

我也试过

SELECT Owner FROM Account
WHERE Balance >= 10000 AND ExpirationDate = DATE_ADD(CURDATE(), INTERVAL 2 DAY);

SELECT Owner FROM Account
WHERE Balance >= 10000 AND DATE_SUB(GETDATE(), INTERVAL 10 DAY);

不用说两种方式都不起作用。

1 个答案:

答案 0 :(得分:2)

如上所述,您的DDL不正确。

以下是针对WebSQL / SQLLite更正的DDL以及您要学习的查询。

CREATE TABLE Account(
    ID INTEGER PRIMARY KEY,
    Owner varchar(50),
    Balance decimal(10,3),
    CreationDate timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    ExpirationDate timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
);

INSERT INTO Account(Owner, Balance, ExpirationDate) Values
    ('Jean Claude Van Damme', 6453, '2023-10-06'),
    ('Peter Paul Rubens', 9999, '2018-06-04'),
    ('Rembrandt Harmenszoon van Rijn', 765549, '2023-10-22'),
    ('Pablo Ruiz y Picasso', 972825, '2019-06-13'),
    ('Michelangelo di Lodovico Buonarroti', 7981, '2022-10-27'),
    ('Raffaello Sanzio da Urbino', 548765, '2018-11-17'),
    ('John Doe', 666745, '2021-12-05'),
    ('Mickey Mouse', 10005, '2020-10-21'),
    ('Vincent Willem van Gogh', 453906, '2021-07-13'),
    ('Oliver Hardy', 1005, '2019-01-26');

SELECT * FROM Account
WHERE Balance >= 10000
AND ExpirationDate > DATE()
AND ExpirationDate < DATE('now','+2 day')