我正在计算 5 个表中的字段数量并显示结果。我目前为单个表执行此操作
$variable = mysql_num_rows(mysql_query("SELECT id FROM table1"));
包含和计数所有id
来自table2
、table3
和的最有效方法是什么?table4
table5
谢谢
用于UNION ALL
组合SELECT
对所有表的查询,以获取所有表的 ID 总数。改为使用从所有表中获取 IDUNION
总数。distinct
$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"));
不要从您的数据库中获取所有行,只需获取 id 的数量。让 MySQL 计数而不是 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;
不要进行 UNION 或 JOIN ,如果您只需要计数,这是一项重量级的工作。
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
尝试这样的联合语法:
$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
"));
完结,祝你好运
第一种方法:
$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);
第二种方法:
$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'];
}
SELECT COUNT(id) FROM table2
等等