Mysql查询,范围内的最大值和最小值不能正常工作,我该如何解决?

时间:2013-12-12 14:41:16

标签: mysql max inner-join between

我有一个名为“dati”的表,其中“anni”列(主键)表示从1960年到2012年的年份(所有年份都是连续的),“governi”列表示表“参考”的参考“和”栏“列是我想要用”governi“表中”presidenti“列中的值来取代的值。 如果我尝试提取所有年份的最小/最大值,它的工作原理。但在这种情况下,我需要在有限的几年范围内(例如从1980年到1990年)提取这个值。问题是不返回任何最大/最小值。 表“dati”和表“governi”连接在“governo”列和“cod”列之间,如数据库模式中所示。

这是数据库结构:

TABLE dati:
    anno INT(4),
    governo VARCHAR(6),
    pil FLOAT(10)
TABLE governi:
    cod VARCHAR(6),
    presidente varchar (50)

这是SQL:

QUERY1:

SELECT a.presidente, b.anno, b.$dato
FROM governi AS a
INNER JOIN dati AS b ON a.cod=b.governo
WHERE b.$dato =(
    SELECT MAX(c.$dato) AS maxpil
    FROM dati AS c
) AND b.anno BETWEEN $inizio AND $fine;

query2:

SELECT a.presidente, b.anno, b.$dato
FROM governi AS a
INNER JOIN dati AS b ON a.cod=b.governo
WHERE b.$dato = (
    SELECT MIN(NULLIF(c.$dato,0)) AS valore
    FROM dati AS c
) AND b.anno BETWEEN $inizio AND $fine;

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

试试这个

SELECT a.presidente, b.anno, b.$dato
FROM governi AS a
INNER JOIN dati AS b ON a.cod=b.governo
WHERE b.$dato =(
    SELECT MAX($dato) AS maxpil
    FROM dati,governi WHERE anno BETWEEN $inizio AND $fine AND governi.cod=dati.govern
) 

SQL Fiddle

答案 1 :(得分:0)

尝试此查询:

SELECT a.presidente, b.anno, q.valore, q.maxpil
FROM governi AS a
INNER JOIN dati AS b ON a.cod=b.governo
JOIN (
    SELECT MAX(anno) AS maxpil,
           MIN(anno) AS valore
    FROM dati AS c
    WHERE c.anno BETWEEN 
             1965    -- $inizio 
          AND 
             2012    -- $fine
) AS q
ON b.anno BETWEEN q.valore AND q.maxpil

演示 - > http://www.sqlfiddle.com/#!2/480e9/14