我一直在努力解决这个问题,因为我无法通过自己的+ google + MySQL文档解决这个问题,我转向你们。
我想检索与特定项目相关的最新客户端ID,按以下方式分组:
如果给定类型的客户端具有相同数量的相关项目,我想获得最新的一个(因此下面是MAX(Client.id)
)。
我的(简化)表:
CREATE TABLE `Client` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`clientType` ENUM ('A', 'B', 'C', 'D') COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8 COLLATE = utf8_unicode_ci;
CREATE TABLE `Item` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8 COLLATE = utf8_unicode_ci;
CREATE TABLE `ClientHasItem` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`clientId` INT(11) NOT NULL,
`itemId` INT(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_ClientHasItem_itemId_Item_id` (`itemId`),
CONSTRAINT `FK_ClientHasItem_clientId_client_id` FOREIGN KEY (`clientId`) REFERENCES `Client` (`id`),
CONSTRAINT `FK_ClientHasItem_itemId_Item_id` FOREIGN KEY (`itemId`) REFERENCES `Item` (`id`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8 COLLATE = utf8_unicode_ci;
示例数据:
INSERT INTO `Client` (`id`, `clientType`)
VALUES
(1,'A'),
(2,'A'),
(3,'B'),
(4,'C'),
(5,'C'),
(6,'D');
INSERT INTO `ClientHasItem` (`id`, `clientId`, `itemId`)
VALUES
(2,1,1),
(3,2,1),
(4,2,2);
(5,3,1),
(6,3,2),
(7,4,1),
INSERT INTO `Item` (`id`, `name`)
VALUES
(1,'Pizza'),
(2,'Hot-Dog');
预期结果(对于Item.id = 1):
1 (because: type A, count=1)
2 (because: type A, count=2)
3 (because: type B, count=2)
4 (because: type C, count=1)
我最接近解决方案的是:
SELECT MAX(Client.id) AS id
FROM `Client`
INNER JOIN `ClientHasItem` ON `Client`.`id` = `ClientHasItem`.`clientId`
INNER JOIN `Item` ON `ClientHasItem`.`itemId` = `Item`.`id`
WHERE (`Item`.`id` = 1) AND (`Client`.`clientType` IN ('A', 'B', 'C'))
GROUP BY `Client`.`clientType`;
计数查询看起来像:
SELECT COUNT(DISTINCT `ClientHasItem`.`itemId`)
FROM `ClientHasItem`
WHERE `ClientHasItem`.`clientId`= MAX(Client.id) // id selected in the previous query.
PS。我只有_full_group_by模式开启,它必须保持这种状态。我的MySQL版本:5.7.10