使用php从sql数据库创建额外的组合html表

时间:2019-03-09 18:34:56

标签: php html sql

在将此帖子标记为双之前,请仔细阅读。我有一个MySQL基,其中有3个表,T1T2T3。他们的数据是这些:

T1:

name  val1  val2    
John    1    2    
Mary    1    2

T2:

name  val3  val4    
John    3    4    
Mark    1    2

T3:

name  val5  val6    
John    5    6    
Mark    3    4    
Mary    4    5

,我想创建以下组合的html表:

name  val1  val2  val3  val4  val5  val6    
John   1      2    3      4    5      6    
Mary   1      2    -      -    4      5    
Mark   -      -    1      2    3      4

对我来说,这似乎很复杂。有什么想法怎么做吗?

3 个答案:

答案 0 :(得分:1)

SELECT TX.NAME,
(SELECT val1 FROM T1
    WHERE T1.NAME = TX.NAME) AS V1,
(SELECT val2 FROM T1
    WHERE T1.NAME = TX.NAME) AS V2,
(SELECT val3 FROM T2
    WHERE T2.NAME = TX.NAME) AS V3,
(SELECT val4 FROM T2
    WHERE T2.NAME = TX.NAME) AS V4,
(SELECT val5 FROM T3
    WHERE T3.NAME = TX.NAME) AS V5,
(SELECT val6 FROM T3
    WHERE T3.NAME = TX.NAME) AS V6
FROM (
SELECT NAME FROM T1
UNION
SELECT NAME FROM T2
UNION
SELECT NAME FROM T3) AS TX

我们可以对每个不同的列使用一个子查询来完成它。

答案 1 :(得分:0)

没有那么复杂。

如果MySQL是您更强的语言,则编写一个查询,以所需列中的所需值(到数组中)将三个表联接起来。

如果PHP是您的强语言,请编写三个查询,从每个表中选择值(分为不同的数组)。然后将这些数组“连接”到具有所需列的一个数组中。

无论哪种情况,您都希望结果是一个数组,每个用户有一个具有6个值的“键”。

您可以直接将结果迭代到html表中。

答案 2 :(得分:0)

使用union allgroup by

select name, sum(val1) as val1, sum(val2) as val2,
       sum(val3) as val3, sum(val4) as val4,
       sum(val5) as val5, sum(val6) as val6
from ((select name, val1, val2, null as val3, null as val4, null as val5, null as val6 from t1
      ) union all
      (select name, null, null, val1, val2, null, null from t2
      )
      (select name, null, null, null, null val1, val2 from t3
      )
     ) t
group by name;

或者,如果您知道t3具有所需的所有行,请使用left join

select t3.name, t1.val1, t1.val2,
       t2.val1 as val3, t2.val2 as val4,
       t2.val1 as val5, t2.val2 as val6
from t3 left join
     t1
     on t3.name = t1.name left join
     t2
     on t3.name = t2.name;

我不推荐full join。创建正确的查询有点棘手,而且很容易犯一个错误,可以过滤掉行。