gpt4 book ai didi

mysql - 查询中的许多项目的乘法计数

转载 作者:行者123 更新时间:2023-11-29 00:51:38 25 4
gpt4 key购买 nike

这是我的查询:

SELECT
`i`.`itemtype` AS `Item`,
`p`.`name`
SUM(`i`.`count`) AS `Count`
FROM `player_items` AS `i`
LEFT JOIN `players` AS `p` ON (`p`.`id` = `i`.`player_id`)
WHERE `i`.`itemtype` IN (2148, 2152, 2160)
AND `i`.`player_id` = " . intval ( $main_Char->getId() ) . "
GROUP BY `i`.`itemtype`
LIMIT 0, 30;

是否有可能为它选择的每个项目增加一个计数?我的意思是 WHERE
i.itemtypeIN (2148, 2152, 2160)它对所有 ID 项目的计数求和:2148, 2152, 2160 我需要它来做同样的事情,但还要乘以每个项目的计数:2148 * 102152 * 1000, 2160 * 10000 然后在 Count 行显示结果。

最佳答案

是的,您可以一次SUM多个列:

SELECT i.itemtype AS Item
, p.name
, SUM(CASE
WHEN itemtype = 2148 THEN i.count
ELSE 0
END) * 10 AS Count
, SUM(CASE
WHEN itemtype = 2152 THEN i.count
ELSE 0
END) * 1000 AS Count1
, SUM(CASE
WHEN itemtype = 2160 THEN i.count
ELSE 0
END) * 10000 AS Count2
FROM player_items AS i
LEFT JOIN players AS p ON i.player_id = p.id
WHERE i.itemtype IN (2148, 2152, 2160)
GROUP BY i.itemtype ASC
LIMIT 0, 30

要将这三列相加,您可以:

SELECT t.itemType AS Item, t.Count, t.Count1, t.Count2
, SUM(t.Count1, t.Count2, t.Count3) AS Total
FROM
(
SELECT i.itemtype AS Item
, p.name
, SUM(CASE
WHEN itemtype = 2148 THEN i.count
ELSE 0
END) * 10 AS Count
, SUM(CASE
WHEN itemtype = 2152 THEN i.count
ELSE 0
END) * 1000 AS Count1
, SUM(CASE
WHEN itemtype = 2160 THEN i.count
ELSE 0
END) * 10000 AS Count2
FROM player_items AS i
LEFT JOIN players AS p ON i.player_id = p.id
WHERE i.itemtype IN (2148, 2152, 2160)
GROUP BY i.itemtype ASC
LIMIT 0, 30
) AS t

或者你可以添加另一个CASE

SELECT i.itemtype AS Item
, p.name
, SUM(CASE
WHEN itemtype = 2148 THEN i.count
ELSE 0
END) * 10 AS Count
, SUM(CASE
WHEN itemtype = 2152 THEN i.count
ELSE 0
END) * 1000 AS Count1
, SUM(CASE
WHEN itemtype = 2160 THEN i.count
ELSE 0
END) * 10000 AS Count2
, SUM(CASE
WHEN itemtype = 2148 THEN (i.count * 10)
WHEN itemtype = 2152 THEN (i.count * 1000)
WHEN itemtype = 2160 THEN (i.count * 10000)
ELSE 0
END) AS Total
FROM player_items AS i
LEFT JOIN players AS p ON i.player_id = p.id
WHERE i.itemtype IN (2148, 2152, 2160)
GROUP BY i.itemtype ASC
LIMIT 0, 30

关于mysql - 查询中的许多项目的乘法计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8319549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com