无法在一段时间内显示信息

时间:2014-08-21 23:17:12

标签: mysql

我试图在一段时间内显示2列之间的条件,如下所示:

以下是demo

以下是信息:

CREATE TABLE clients
(date_birth date, [date_anniversary] date)
;

INSERT INTO clients
([date_birth], [date_anniversary])
VALUES
('1911-01-20',NULL ),
('1921-01-20',NULL ),
('1931-01-20',NULL ),
('1941-01-20',NULL ),
('1951-01-20',NULL ),
('1961-01-20',NULL ),
('1971-01-20',NULL ),
('1981-01-20',NULL ),
('1991-01-20',NULL ),
(NULL, '1998-02-13'),
(NULL, '1999-02-13'),
(NULL, '2000-02-13'),
(NULL, '2001-02-13'),
(NULL, '2002-02-13'),
(NULL, '2003-02-13'),
(NULL, '2004-02-13'),
(NULL, '2005-02-13'),
(NULL, '2006-02-13');

我试图表明:

('1911-01-20',NULL ),
('1921-01-20',NULL ),
('1931-01-20',NULL ),
('1941-01-20',NULL ),
('1951-01-20',NULL ),
('1961-01-20',NULL ),
('1971-01-20',NULL ),
('1981-01-20',NULL ),
('1991-01-20',NULL ),
(NULL, '1998-02-13'),
(NULL, '1999-02-13'),

我试过这个但是没有用:

select * from clients where date_birth OR date_anniversary BETWEEN '1910-01-01' AND '2000-01-01'

请有人帮助我吗?

1 个答案:

答案 0 :(得分:1)

你必须写完整的条件:

select * from clients 
where 
    date_birth BETWEEN '1910-01-01' AND '2000-01-01'
OR 
    date_anniversary BETWEEN '1910-01-01' AND '2000-01-01'

在您的特殊情况下:两列中只有一列包含非NULL值,您可以使用函数COALESCE,它返回参数列表的第一个非空值:

select 
    * from clients 
where 
    COALESCE(date_birth, date_anniversary) BETWEEN '1910-01-01' AND '2000-01-01';

但即使这看起来更简单,也可能是性能比第一种解决方案更差。你应该查看EXPLAIN。

在您的(已修改的)Demo

中查看