简化涉及“按日期排序限制1”的多个SQL

时间:2013-08-27 15:14:43

标签: sql sqlite

我有以下SQL来提取给定invoice的最新bill

SELECT  "invoices".* FROM "invoices"  WHERE "invoices"."bill_id" = ?  ORDER BY issue_date DESC LIMIT 1

我为一个集合中的每个bill_id运行它,比如说[1, 5, 7, 9]。有没有办法只用一个执行这4个SQL命令?

编辑::为了澄清,我有4张账单,每张账单都有多张发票。我想要每张账单的最新发票。总共有4张发票。

架构:

CREATE TABLE "bills" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar(255))
CREATE TABLE "invoices" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "issue_date" datetime, "amount_cents" integer, "bill_id" integer)

2 个答案:

答案 0 :(得分:1)

您可以尝试此查询:

 SELECT  i.* 
 FROM invoices AS i
 WHERE i.bill_id in (1,5,7,9)
 AND i.issue_date = (SELECT li.issue_date 
                     FROM invoices AS li
                     WHERE i.bill_id = li.bill_id
                     ORDER BY li.issue_date DESC LIMIT 1)

请参阅SQLFIDDLE:http://sqlfiddle.com/#!5/f4f27/3/0

或者您可以使用MAX函数和GROUP BY子句

来执行此操作
SELECT  i.* 
FROM invoices AS i
WHERE i.bill_id in (1,5,7,9)
AND i.issue_date = (SELECT MAX(li.issue_date)
                    FROM invoices AS li
                    WHERE i.bill_id = li.bill_id
                    GROUP BY li.bill_id)

请参阅SQLFIDDLE:http://sqlfiddle.com/#!5/f4f27/4/0

答案 1 :(得分:1)

您可以简单地使用:

SELECT *
FROM  invoices
WHERE bill_id IN (1,5,7,9)
GROUP BY bill_id HAVING MAX(issue_date);

测试相同的数据@Fabien帖子:SQL Fiddle