Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP running Union All SQL Statement

im trying to combine two tables together, but whenever i run the program, this happens. enter image description here

As you can see i've echoed out the sql statement. Here are my codes.

$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;

I'd like to show count(*) as in the photo, as a third column to the genrated table.

like image 381
mctjl_1997 Avatar asked Feb 01 '26 23:02

mctjl_1997


2 Answers

You don't need UNION select here, instead you can use subquery:

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

and in PHP you use $row['repeater_sum'].. etc

like image 142
George Garchagudashvili Avatar answered Feb 04 '26 13:02

George Garchagudashvili


When you union two or more queries together each query should have the same columns of data with same data type for example :

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

Replace your query with this format

like image 43
Mohammad Fareed Avatar answered Feb 04 '26 11:02

Mohammad Fareed