I'm stuck on a sum in sql. What I'm trying to do is the following:
I have a table which stores id's of items. Those id's are linked to another table 'library' with the description, the names and the points of those items.
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'"
.
If these are numeric IDs you can avoid the single quote marks, they are used for strings.
If the ids are coming from a table, then you should use join
, in
, or 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. That is inelegant, inefficient, and more work than necessary.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.