我正在使用 mysql。我不在乎有多少组返回,但如果一个组有超过 4 个项目,我只想要前 4 个。我如何编写一个每组只返回 4 行的语句?作为临时修复,我只是将它们全部归还并在代码中将其过滤掉。它仍然非常快,但如果我知道语法会更容易
最佳答案
如果我正确理解您的问题,我相信以下答案应该大致满足您的需求(注意:由于未提供您的表结构,我以两个测试表及其关联的插入作为示例):
给定这些表格和数据:
DROP TABLE IF EXISTS tCustomer;
CREATE TABLE tCustomer (
customerId INT(11) UNSIGNED NOT NULL auto_increment,
name VARCHAR(8),
PRIMARY KEY (customerId)
) AUTO_INCREMENT=1;
INSERT INTO tCustomer VALUES
(NULL, 'Alex'),
(NULL, 'Bob'),
(NULL, 'Carl')
;
DROP TABLE IF EXISTS tPurchases;
CREATE TABLE tPurchases (
purchaseId INT(11) UNSIGNED NOT NULL auto_increment,
customerId INT(11) UNSIGNED NOT NULL,
amount DECIMAL(9,2),
purchaseDate DATETIME,
PRIMARY KEY (purchaseId),
CONSTRAINT fk_customer FOREIGN KEY (customerId) REFERENCES tCustomer (customerId)
) AUTO_INCREMENT=1;
INSERT INTO tPurchases VALUES
(NULL, 1, 1.00, '2011-01-01 08:00'),
(NULL, 1, 1.01, '2011-01-02 08:00'),
(NULL, 1, 1.02, '2011-01-03 08:00'),
(NULL, 1, 1.03, '2011-01-04 08:00'),
(NULL, 1, 1.04, '2011-01-05 08:00'),
(NULL, 1, 1.05, '2011-01-06 08:00'),
(NULL, 2, 1.01, '2011-01-01 08:00'),
(NULL, 2, 1.02, '2011-01-02 08:00'),
(NULL, 3, 1.01, '2011-01-02 08:00'),
(NULL, 3, 1.02, '2011-01-04 08:00'),
(NULL, 3, 1.03, '2011-01-08 08:00')
;
以下 SQL 将按客户退回不超过 4 个最近的购买来选择购买数据:
SELECT
tC.customerId, tC.name, tP.purchaseDate, tP.amount, COUNT(tPNewer.customerId) newerCt
FROM
tCustomer tC
INNER JOIN tPurchases tP ON tC.customerId = tP.customerId
LEFT OUTER JOIN tPurchases tPNewer ON tP.customerId = tPNewer.customerId AND tPNewer.purchaseId > tP.purchaseId
GROUP BY
tC.customerId,
tC.name,
tP.purchaseDate,
tP.amount
HAVING
newerCt < 4 -- Ignore rows that have more than 3 newer records
ORDER BY
tC.customerId,
tP.purchaseDate desc
;
这是此选择的结果输出(请注意,Alex 最旧的交易不存在):
+------------+------+---------------------+--------+---------+
| customerId | name | purchaseDate | amount | newerCt |
+------------+------+---------------------+--------+---------+
| 1 | Alex | 2011-01-06 08:00:00 | 1.05 | 0 |
| 1 | Alex | 2011-01-05 08:00:00 | 1.04 | 1 |
| 1 | Alex | 2011-01-04 08:00:00 | 1.03 | 2 |
| 1 | Alex | 2011-01-03 08:00:00 | 1.02 | 3 |
| 2 | Bob | 2011-01-02 08:00:00 | 1.02 | 0 |
| 2 | Bob | 2011-01-01 08:00:00 | 1.01 | 1 |
| 3 | Carl | 2011-01-08 08:00:00 | 1.03 | 0 |
| 3 | Carl | 2011-01-04 08:00:00 | 1.02 | 1 |
| 3 | Carl | 2011-01-02 08:00:00 | 1.01 | 2 |
+------------+------+---------------------+--------+---------+
关于mysql - 我如何限制每组的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7441844/