我需要创建一个查询,以便根据日期间隔返回N行。这很简单,但我不能:/
基本查询:
SELECT
f.many_fields
FROM
tb_foo f
WHERE
f.id_foo = 14
此查询根据我的ID返回1行。 但是,我在'2012-10-30'的日期间隔'2012-10-10'应用此查询,最后基本查询将根据日期间隔的差异返回20行。
可以做到吗?
SELECT
f.many_fields,
bar.*
FROM
tb_foo f,
(SELECT x FROM dual limit DATEDIFF('2012-10-10','2012-10-30')) bar
WHERE
f.id_foo = 14
真实查询:
SELECT
m.id_matricula,
a.nome
FROM
tb_matricula m
inner join tb_aluno a on (a.id_aluno = m.id_matricula)
WHERE
m.id_matricula = 14
开始日期= 2012-10-10 截止日期= 2012-10-30
我将在iReport上使用此结果,根据此日期之间的差异构建一个包含行数的网格。
基于Google搜索的示例:
SELECT
CONCAT( dt.d ,'-' ,days.d ) AS dates
FROM
(
SELECT
CONCAT( a1 ,b1 ) AS d
FROM
(
SELECT
'0' AS a1
UNION ALL SELECT
'1'
UNION ALL SELECT
'2'
UNION ALL SELECT
'3'
) a JOIN(
SELECT
'0' AS b1
UNION ALL SELECT
'1'
UNION ALL SELECT
'2'
UNION ALL SELECT
'3'
UNION ALL SELECT
'4'
UNION ALL SELECT
'5'
UNION ALL SELECT
'6'
UNION ALL SELECT
'7'
UNION ALL SELECT
'8'
UNION ALL SELECT
'9'
) b
WHERE
CONVERT(
CONCAT( a1 ,b1 ) ,
UNSIGNED
) <=(
SELECT
DAY(
CONCAT( '2012-10' ,'-01' ) + INTERVAL 1 MONTH - INTERVAL 1 DAY
)
)
AND CONCAT( a1 ,b1 ) <> '00'
) days JOIN(
SELECT
'2012-10' AS d
) dt
HAVING
dates BETWEEN '2012-10-02' AND '2012-10-05'
ORDER BY
dates
;
答案 0 :(得分:0)
我找到了解决方法。使用子查询,我可以根据日期间隔返回许多行,与主查询没有任何关系。所以我有这个:
SELECT
datas. * ,
m.id_matricula ,
p.nome
FROM
tb_matricula m INNER JOIN tb_aluno a
ON(
a.id_aluno = m.id_aluno
) INNER JOIN tb_perfil p
ON(
p.id_perfil = a.id_perfil
) ,
(
SELECT
CONCAT( dt.d ,'-' ,days.d ) AS dates
FROM
(
SELECT
CONCAT( a1 ,b1 ) AS d
FROM
(
SELECT
'0' AS a1
UNION ALL SELECT
'1'
UNION ALL SELECT
'2'
UNION ALL SELECT
'3'
) a JOIN(
SELECT
'0' AS b1
UNION ALL SELECT
'1'
UNION ALL SELECT
'2'
UNION ALL SELECT
'3'
UNION ALL SELECT
'4'
UNION ALL SELECT
'5'
UNION ALL SELECT
'6'
UNION ALL SELECT
'7'
UNION ALL SELECT
'8'
UNION ALL SELECT
'9'
) b
WHERE
CONVERT(
CONCAT( a1 ,b1 ) ,
UNSIGNED
) <=(
SELECT
DAY(
CONCAT( '2012-02' ,'-01' ) + INTERVAL 1 MONTH - INTERVAL 1 DAY
)
)
AND CONCAT( a1 ,b1 ) <> '00'
) days JOIN(
SELECT
'2012-02' AS d
) dt
UNION ALL SELECT
CONCAT( dt.d ,'-' ,days.d ) AS dates
FROM
(
SELECT
CONCAT( a1 ,b1 ) AS d
FROM
(
SELECT
'0' AS a1
UNION ALL SELECT
'1'
UNION ALL SELECT
'2'
UNION ALL SELECT
'3'
) a JOIN(
SELECT
'0' AS b1
UNION ALL SELECT
'1'
UNION ALL SELECT
'2'
UNION ALL SELECT
'3'
UNION ALL SELECT
'4'
UNION ALL SELECT
'5'
UNION ALL SELECT
'6'
UNION ALL SELECT
'7'
UNION ALL SELECT
'8'
UNION ALL SELECT
'9'
) b
WHERE
CONVERT(
CONCAT( a1 ,b1 ) ,
UNSIGNED
) <=(
SELECT
DAY(
CONCAT( '2012-03' ,'-01' ) + INTERVAL 1 MONTH - INTERVAL 1 DAY
)
)
AND CONCAT( a1 ,b1 ) <> '00'
) days JOIN(
SELECT
'2012-03' AS d
) dt
ORDER BY
dates
) datas
WHERE
m.id_matricula = 42
and
datas.dates BETWEEN '2012-02-25' AND '2012-03-05';
为ID = 42和3天的日期差异运行此语句我有:
DATES, ID_MATRICULA, NOME
2012-02-25 42 R ANDRE F DOMINGOS
2012-02-26 42 R ANDRE F DOMINGOS
2012-02-27 42 R ANDRE F DOMINGOS