[英]Sql query; sum fields
I'm stuck on a sum in sql. 我被困在sql中。 What I'm trying to do is the following: 我想要做的是以下内容:
I have a table which stores id's of items. 我有一个表,用于存储项目的ID。 Those id's are linked to another table 'library' with the description, the names and the points of those items. 这些ID链接到另一个表“库”,其中包含这些项目的描述,名称和要点。
Now I need to grab some different items in the library and calculate the total of those points together. 现在,我需要在库中获取一些不同的项目,并一起计算这些点的总数。
I hope I was clear enough. 我希望我很清楚。 Beneath the query I'm using: 在我正在使用的查询下:
"SELECT SUM(`points`) AS `total` FROM `library` WHERE `id` = '". $row2['lid'] ."'"
a possible way to do it is: 一种可能的方法是:
"SELECT SUM(`points`) AS `total` FROM `library` WHERE `id` in (". $IDlist .")"
Where $IDList
is a comma separated list of your IDs, like for example "'1', '2', '3'"
. 其中$IDList
是ID的逗号分隔列表,例如"'1', '2', '3'"
。
If these are numeric IDs you can avoid the single quote marks, they are used for strings. 如果这些是数字ID,则可以避免使用单引号,它们用于字符串。
If the ids are coming from a table, then you should use join
, in
, or exists
. 如果ID来自表,则应使用join
, in
或exists
。 Something like: 就像是:
select sum(points) as total
from library l join
otheridtable oit
on l.id = oit.id;
You should not move the ids from the database to the application layer, just to stuff them into a string and send them back to the database. 你不应该从数据库到应用层的移动的ID,只是将它们塞进一个字符串,并送他们回数据库。 That is inelegant, inefficient, and more work than necessary. 那是微不足道的,低效的,并且比必要的工作更多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.