是否可以对任意一组值运行查询?

时间:2015-01-08 20:29:42

标签: mysql

我试图弄清楚如何根据一系列值构建查询(而不是在业务逻辑中以编程方式处理)。

特定的愿望是从表中提取给定时间范围内存在的行。所以,在伪我喜欢做类似

的事情
set timeframes as ["'2014-01-01' and '2014-01-31'",  "'2014-02-01' and '2014-02-28'" ,  "'2014-03-01' and '2014-03-31'", ... etc for the rest of the year];

select t , 
(select count(id) from users where registration_date between t)

from timeframes;

这将导致表格看起来像

2014-01-01' and '2014-01-31  |   455
2014-02-01' and '2014-02-28  |   773
etc.

修改 需要说明的是,这个例子(有几个月)只是我尝试做的一个例子......在我所拥有的真实场景中,标准列表可能是完全随意的,所以,我真的很感激利用mysql构造的答案,如 MONTH()方法,这不是我想在这里解决的真正问题。

2 个答案:

答案 0 :(得分:1)

使用类似:

SELECT 
    MONTH(dateCol), 
    COUNT(*) 
FROM table 
WHERE datecol BETWEEN '2014-01-01' AND '2014-12-31' 
GROUP BY MONTH(dateCol) 
ORDER BY MONTH(dateCol)

答案 1 :(得分:1)

我无法弄清楚如何以提议的确切方式帮助解决您的问题,但设法制定了类似的(我认为)解决方案( here you may find SQL Fiddle for the below ):

数据结构

CREATE TABLE timeframes 
(
  tf_start DATE  NOT NULL,
  tf_end DATE NOT NULL,
  PRIMARY KEY(tf_start, tf_end)  
);

CREATE TABLE users 
(
  id int primary key NOT NULL,
  registration_date DATE
);

INSERT INTO timeframes
VALUES
('2014-01-01' , '2014-01-31'),  
('2014-02-01' , '2014-02-28'),  
('2014-03-01' , '2014-03-31');


INSERT INTO users
VALUES
(455, '2014-01-14'),
(773, '2014-02-17');

查询

在时间范围内选择用户数:

select 
    CONCAT('''', DATE_FORMAT(t.tf_start, '%Y-%m-%d'), ''' and ''', DATE_FORMAT(t.tf_end, '%Y-%m-%d'), '''') AS tf, 
    (select count(id) from users where registration_date between t.tf_start AND t.tf_end) AS user_count
from 
    timeframes t;

结果:

TF                              |   USER_COUNT
==============================================
'2014-01-01' and '2014-01-31'   |   1
'2014-02-01' and '2014-02-28'   |   1
'2014-03-01' and '2014-03-31'   |   0

要将每个用户加入registration_date所属的时间范围:

select 
  CONCAT('''', DATE_FORMAT(t.tf_start, '%Y-%m-%d'), ''' and ''', DATE_FORMAT(t.tf_end, '%Y-%m-%d'), '''') AS tf,
  users.id
from 
  timeframes t
  LEFT OUTER JOIN users 
     ON users.registration_date between t.tf_start AND t.tf_end;

和结果:

TF                              |   ID
===========================================
'2014-01-01' and '2014-01-31'   |   455
'2014-02-01' and '2014-02-28'   |   773
'2014-03-01' and '2014-03-31'   |   (null)

我希望它有所帮助。