简体   繁体   中英

SUM points from table

I have table with files and their have their points/score. Iam trying to summarize those points and print it. I have a where clause for id files, but if I select random files it has same score as others like where clause isnt working.

$id is correct for each file.

This is my query:

$result = mysql_query("SELECT *,SUM(body) FROM soubory, users, hodnoti WHERE
soubory.id='".$id."' AND soubory.users_id = users.id");

hodnoti table

users_ID  soubory_id  body
  14        44         7 
  15        44         9

And now, if there is no record (in table hodnoti) for soubory_id = 45 the result is same as for 44 despite of where clause.

users table

id   nick
14   user1
15   user2

soubory table

id   nazev  users_id
44   file1  14
45   file2  14

That query should help me print this:

Who uploaded, nazev(title) of the file and then points. But if file2 has no record in table hodnoti, still has score of file1. Hope it helps.

$sql = "SELECT *, SUM(hodnoti.body) as sum FROM soubory 
    INNER JOIN users ON soubory.users_id = users.id
    INNER JOIN hodnoti ON soubory.id = hodnoti.soubory_id
    WHERE soubory.id='".$id."' ";

$result = mysql_query($sql);

This query works for me. When i set id=44 and get a result and when set id=45 and get all null value. i have attached two result image. I have just create table and insert your given data and run query on phpmyadmin sql tab query box. You can try this for check your query works or not.

在此处输入图片说明在此处输入图片说明

Use JOIN .

$sql = "SELECT *, SUM(hodnoti.body) as sum FROM soubory 
        INNER JOIN users ON soubory.users_id = users.id
        INNER JOIN hodnoti ON soubory.id = hodnoti.soubory_id
        WHERE soubory.id='".$id."' ";

$result = mysql_query($sql);


SUGGESTION: Above is a direct answer for your question. Avoid using mysql_* statements as they are deprecated now. Learn mysqli_* or PDO and start implementing that.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM