如何选择低于值的最新记录

时间:2014-11-19 10:32:40

标签: mysql sql

我有一张名为指挥的表。我想选择date小于my_value的最新记录。

+----+-----------+------+
| id | program   | date |
+----+-----------+------+
| 1  | program 1 | 1    |
| 2  | program 1 | 3    |
| 3  | program 2 | 3    |
| 4  | program 1 | 5    |
| 5  | program 1 | 7    |
+----+-----------+------+

如果我们认为my_value是4,那么输出将是:

+----+-----------+------+
| id | program   | date |
+----+-----------+------+
| 2  | program 1 | 3    |
| 3  | program 2 | 3    |
+----+-----------+------+

如何通过SQL选择记录?

4 个答案:

答案 0 :(得分:1)

SELECT * FROM Conductor
WHERE `date` = (SELECT max(`date`) FROM Conductor
                WHERE `date` < myvalue )

答案 1 :(得分:0)

您可以尝试以下查询:

SELECT * FROM conductor
WHERE date = (SELECT date FROM conductor 
              WHERE date < my_value ORDER BY DESC limit 1);

这应该可以满足您的期望!

答案 2 :(得分:0)

SELECT * FROM Conductor
WHERE date IN (SELECT max(date) FROM Conductor
                WHERE date < myvalue )

答案 3 :(得分:0)

 DROP TABLE IF EXISTS my_table;

 CREATE TABLE my_table
 (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
 ,program   VARCHAR(12) NOT NULL
 ,date INT NOT NULL
 );

 INSERT INTO my_table VALUES
 (1  ,'program 1',1),
 (2  ,'program 1',3),
 (3  ,'program 2',3),
 (4  ,'program 1',5),
 (5  ,'program 1',7);

 SELECT * FROM my_table;
 +----+-----------+------+
 | id | program   | date |
 +----+-----------+------+
 |  1 | program 1 |    1 |
 |  2 | program 1 |    3 |
 |  3 | program 2 |    3 |
 |  4 | program 1 |    5 |
 |  5 | program 1 |    7 |
 +----+-----------+------+

 SELECT x.* 
   FROM my_table x 
   JOIN 
      ( SELECT program
             , MAX(date) max_date 
          FROM my_table 
         WHERE date < 4 
         GROUP 
            BY program
      ) y 
     ON y.program = x.program 
    AND y.max_date = x.date;
 +----+-----------+------+
 | id | program   | date |
 +----+-----------+------+
 |  2 | program 1 |    3 |
 |  3 | program 2 |    3 |
 +----+-----------+------+