1

我有 5 个不同的 MySql 表,即:

u_t (uid, pwd, field1, field2)

t_1(tid_1、ut_uid、field_1、field_2、点)

t_2(tid_2、ut_uid、field_1、field_2、点)

t_3(tid_3、ut_uid、field_1、field_2、点)

t_4(tid_4、ut_uid、field_1、field_2、点)

PS: uid=pk , tid_1,2,3,4=pk, ut_uid=fk

以上所有表格都具有基于某些独特功能的一些信息。

现在我想使用 PHP 从每个表中为每个用户获取点的总和,以用于存储和显示目的。

4

2 回答 2

3

尝试

select u_t.uid, 
       sum(t_1.points+t_2.points+t_3.points+t_4.points+t_5.points) as total_p
from u_t
left outer join t_1 on t_1.ut_uid = u_t.uid
left outer join t_2 on t_2.ut_uid = u_t.uid
left outer join t_3 on t_3.ut_uid = u_t.uid
left outer join t_4 on t_4.ut_uid = u_t.uid
group by u_t.uid
于 2012-08-23T11:41:46.313 回答
0

一个更丑陋的版本:

SELECT ut.uid, sum(t1.pts + t2.pts + t3.pts + t4.pts) total
FROM u_t ut
LEFT JOIN
(
  SELECT ut_uid, sum(points) pts
  FROM t_1
  GROUP BY ut_uid
) t1
  on ut.uid = t1.ut_uid
LEFT JOIN
(
  SELECT ut_uid, sum(points) pts
  FROM t_2
  GROUP BY ut_uid
) t2
  on ut.uid = t2.ut_uid
LEFT JOIN
(
  SELECT ut_uid, sum(points) pts
  FROM t_3
  GROUP BY ut_uid
) t3
  on ut.uid = t3.ut_uid
LEFT JOIN
(
  SELECT ut_uid, sum(points) pts
  FROM t_4
  GROUP BY ut_uid
) t4
  on ut.uid = t4.ut_uid
GROUP BY ut.uid
于 2012-08-23T11:45:05.560 回答