PHP运行Union All SQL Statement

时间:2016-06-20 09:58:22

标签: php mysql phpmyadmin

我试图将两个表组合在一起,但每当我运行程序时,都会发生这种情况。 enter image description here

正如你所看到的,我已经回应了sql语句。这是我的代码。

$queryc1 = "select sum(repeater),sum(membersigned) from sales UNION ALL select count(*) from approach;"; //DO INNERJOIN PRACTISE
$resultc1 = mysqli_query($dbconn,$queryc1);
echo "<table>
<tr>
<th>Repeater</th>
<th>Members</th>
<th>Approach</th>
</tr>";
while($row = mysqli_fetch_array($resultc1)) {
    echo "<tr>";
    echo "<td>" . $row['sum(repeater)'] . "</td>";
    echo "<td>" . $row['sum(membersigned)'] . "</td>";
    echo "<td>" . $row['count(*)'] . "</td>";
    echo "</tr>";
}
echo "</table>";
echo $queryc1;

我想在照片中显示count(*),作为生成表格的第三列。

2 个答案:

答案 0 :(得分:2)

当您将两个或多个查询合并在一起时,每个查询应具有相同数据类型的相同数据列,例如:

SELECT SUM(repeater),SUM(membersigned) FROM sales
UNION
SELECT Text1,Text2 FROM approach

用此格式替换您的查询

答案 1 :(得分:2)

你不需要在这里选择UNION,而是可以使用子查询:

select sum(repeater) as repeater_sum,
       sum(membersigned) as membersigned_sum,
       (select count(*) from approach) as approach_count
from sales;

在PHP中使用$row['repeater_sum'] ..等等