当我从两列获取数据时,如何计算?

时间:2013-06-01 08:04:27

标签: mysql sql join

我在SQL中有2个表。

hfm_files =>  id, user_id, etc...
downloaded => id, hfm_file_id, etc... 

我知道我的user id。如何计算使用简单SQL的一个文件的下载量? 我试图做一些查询,但我无法做到:

UPDATE user u
SET u.affilite_pont = (SELECT COUNT(*) FROM downloaded vm WHERE

2 个答案:

答案 0 :(得分:2)

尝试通过加入两个表来计算:

SELECT COUNT(d.ID) 
  FROM downloaded d
  JOIN hfm_files h
    ON d.hfm_file_id = h.id
 WHERE h.user_id = 1;

所以你更新查询应该是:

UPDATE user u
SET u.affilite_pont = (
                        SELECT COUNT(d.ID) 
                          FROM downloaded d
                          JOIN hfm_files h
                            ON d.hfm_file_id = h.id
                         WHERE h.user_id = 1;
                      )
WHERE ...

答案 1 :(得分:1)

SELECT COUNT(t1.id) FROM 
downloaded t1, hfm_files t2 
WHERE t2.id = t1.hfm_file_id 
AND t2.user_id = <user_id>