我正在计算5个表中的字段数量并显示结果。我目前为单个表
执行此操作 $variable = mysql_num_rows(mysql_query("SELECT id FROM table1"));
从id
,table2
,table3
和table4
中包含和统计所有table5
的最有效方法是什么?
由于
答案 0 :(得分:3)
使用UNION ALL
组合所有表的SELECT
查询,以获取所有表中的ID总数。请使用UNION
来获取所有表格中distinct
个ID的总数。
$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"));
答案 1 :(得分:2)
不要从数据库中获取所有行,只需获取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,如果你只是需要计算,这是一项重量级的工作。
答案 2 :(得分:1)
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
答案 3 :(得分:0)
SELECT COUNT(id) FROM table2
等
答案 4 :(得分:0)
尝试这样的联合语法:
$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
"));
结束,祝你好运
答案 5 :(得分:0)
第一种方法:
$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'];
}