简体   繁体   中英

mysql_num_rows from multiple tables

I'm looking to count the amount of fields in 5 tables and display a result. I currently do this for a single table

    $variable = mysql_num_rows(mysql_query("SELECT id FROM table1"));

What is the most efficient way to include and count all id from table2 , table3 , table4 and table5 ?

Thanks

Use UNION ALL to combine the SELECT queries on all the tables to get the total number of IDs from all the tables. Use UNION instead to get total number of distinct IDs from all the tables.

$variable = mysql_num_rows(mysql_query("
    "SELECT id FROM table1 " .
    "UNION ALL " .
    "SELECT id FROM table2 " .
    "UNION ALL " .
    "SELECT id FROM table3 " .
    "UNION ALL " .
    "SELECT id FROM table4 " .
    "UNION ALL " .
    "SELECT id FROM table5"));

Don't get all rows from your DB, just get the num of id's. Let MySQL count instead of PHP.

    $variable1 = mysql_query("SELECT COUNT(id) FROM table1");
    $variable2 = mysql_query("SELECT COUNT(id) FROM table2");
    $variable3 = mysql_query("SELECT COUNT(id) FROM table3");
    $variable4 = mysql_query("SELECT COUNT(id) FROM table4");
    $variable5 = mysql_query("SELECT COUNT(id) FROM table5");

    $variable = $variable1 + $variable2 + $variable3 + $variable4 +$variable5;

Don't make UNION or JOIN neither, it's a heavywight job if you just need the count.

SELECT count(t1.id)+count(t2.id)+count(t3.id)+count(t4.id)+count(t5.id) from table1 as t1, table2 as t2, table3 as t3, table4 as t4, table5 as t5

SELECT COUNT(id) FROM table2

等等

try union syntax like this:

$variable = mysql_num_rows(mysql_query("
SELECT * FROM(
  SELECT id FROM table1
  UNION
  SELECT id FROM table2
  UNION
  SELECT id FROM table3
  UNION
  SELECT id FROM table4
  UNION
  SELECT id FROM table5
)unionNum
"));

Finish, good luck

First Method:

$query = mysql_query("
    select * from(
        SELECT id FROM table1
        union
        SELECT id FROM table2
        union
        SELECT id FROM table3
        union
        SELECT id FROM table4
    )
");
while ($row = mysql_fetch_assoc($query)) {
    //some operations
}
$variable = mysql_num_rows($query);

Second Method:

$query = mysql_query("
    select count(*) cnt from(
        SELECT id FROM table1
        union
        SELECT id FROM table2
        union
        SELECT id FROM table3
        union
        SELECT id FROM table4
    )
");

while ($row = mysql_fetch_assoc($query)) {
    $variable = $query['cnt'];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM