在cel值之后从表中选择

时间:2016-09-15 08:44:41

标签: mysql

我想从MySQL表中选择最后一个值之后的所有记录。 这是一个例子

MyTable的

+--------------------+--------------------+--------------------+--------------------+
|    date (DATE)     |Product_id  (INT fk)|   Quantite (INT)   |type (ENUM('S', 'R')|
+--------------------+--------------------+--------------------+--------------------+
|    2016-09-20      |         1          |         15         |         R          |
|    2016-09-21      |         1          |         20         |         S          |
|    2016-09-23      |         1          |         19         |         R          |
|    2016-09-28      |         1          |         30         |         S          |
|    2016-09-30      |         1          |         20         |         S          |
+--------------------+--------------------+--------------------+--------------------+

我想要一个查询来获取类型为S

的最后一行

这是我需要的输出

+--------------------+--------------------+--------------------+--------------------+
|    date (DATE)     |Product_id  (INT fk)|   Quantite (INT)   |type (ENUM('S', 'R')|
+--------------------+--------------------+--------------------+--------------------+
|    2016-09-28      |         1          |         30         |         S          |
|    2016-09-30      |         1          |         20         |         S          |
+--------------------+--------------------+--------------------+--------------------+

1 个答案:

答案 0 :(得分:2)

只需使用LIMIT

SELECT *
FROM YourTable t
WHERE t.type = 'S'
ORDER BY t.date DESC
LIMIT 1;

如果您想要每个ID,那么您可以使用NOT EXISTS()

SELECT * FROM YourTable t
WHERE NOT EXISTS (SELECT 1 FROM YourTable s
                  WHERE s.product_id = t.product_id
                    AND s.type = 'S'
                    AND s.date > t.date)
  AND t.type = 'S'

编辑:如果我理解正确,您希望在S类型的最后一条记录之后输入R类型的所有记录,如果是这样的话:

SELECT * FROM YourTable t
WHERE NOT EXISTS (SELECT 1 FROM YourTable s
                  WHERE s.product_id = t.product_id
                    AND s.type = 'R'
                    AND s.date > t.date)
  AND t.type = 'S'