0

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

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)
4

2 回答 2

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

于 2013-08-27T16:20:57.477 回答
1

您可以简单地使用:

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

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

于 2013-08-27T16:58:08.140 回答