我有一张表,可以为商店分配预算。
我想从当前月份获得所有商店的记录,因为我写的查询是:
SELECT * FROM table_budget WHERE store IN ([$STORE$]) AND MONTH(Date) = MONTH(CURRENT_DATE())
AND YEAR(Date) = YEAR(CURRENT_DATE());
但如果商店本月有两个或两个以上的预算,我想获得最新记录。
答案 0 :(得分:0)
将此添加到查询的末尾:
AND NOT EXISTS
(
SELECT * FROM table_budget t2
WHERE t2.Store=table_budget.Store and t2.Date>table_budget.Date
)
答案 1 :(得分:0)
自我加入获取每家商店的最新记录
SELECT
a.*
FROM
table_budget a
LEFT JOIN table_budget b
ON a.store = b.store
AND a.Date < b.Date
WHERE a.store IN ([ $STORE$ ])
AND MONTH(a.Date) = MONTH(CURRENT_DATE())
AND YEAR(a.Date) = YEAR(CURRENT_DATE())
AND b.store IS NULL ;
答案 2 :(得分:0)
您也可以尝试使用 LAST 功能,但并非所有应用程序都支持
因此,如前所述,解决方法解决方案是使用 ORDER BY ,然后使用 DESC 。 如果您只想要最后一条记录,请添加 LIMIT
e.g。 SELECT column_name FROM table_name ORDER BY column_name DESC 限制1;
答案 3 :(得分:0)
试试这个:
SELECT * FROM table_budget WHERE store IN ([$STORE$]) AND MONTH(Date) = MONTH(CURRENT_DATE())
AND YEAR(Date) = YEAR(CURRENT_DATE()) ORDER BY Date DESC
LIMIT 1;