Forum Moderators: coopster

Message Too Old, No Replies

Sum of two sql queries

         

chrissim

8:09 am on Aug 23, 2009 (gmt 0)

10+ Year Member



Guys this is a very basic question but i am not able to find the solution. Hope somebody comes up with solution for me.

My requirement is to add the counts of two tables.

$data = mysql_query("SELECT * FROM Table1")
$number=mysql_num_rows($data);

select * from table1 ; it returns 158
select * from table2; it returns 30

Now i want to have result in single query as 188

can somebody help me?

Little_G

10:42 am on Aug 23, 2009 (gmt 0)

10+ Year Member



Hi,

You should be able to do that in the query, so something like:

SELECT COUNT(table1.*) + COUNT(table2.*) AS sum FROM table1, table2
(untested)

Andrew

Little_G

11:00 am on Aug 23, 2009 (gmt 0)

10+ Year Member



Hi,

Ok, so I tested the last one and it doesn't work but this does:

SELECT (SELECT COUNT(*) FROM table1) + (SELECT COUNT(*) FROM table2) AS sum
.

Andrew

chrissim

1:30 pm on Aug 23, 2009 (gmt 0)

10+ Year Member



hi,

I've tested them as advice but it gave me wrong query. It return the query result as 1 instead of 188.

Little_G

7:17 pm on Aug 23, 2009 (gmt 0)

10+ Year Member



Hi,

You'll want to fetch the value returned by mysql rather than using mysql_num_rows which tells you how many rows were returned by the query, which in this case will always be 1.

$row = mysql_fetch_assoc($data);
$sum = $row['sum'];

Andrew

chrissim

3:08 am on Aug 24, 2009 (gmt 0)

10+ Year Member



Thanks Little_G, everything turns out good now and it works like a champ:)