2

我正在计算 5 个表中的字段数量并显示结果。我目前为单个表执行此操作

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

包含和计数所有id来自table2table3和的最有效方法是什么?table4table5

谢谢

4

6 回答 6

3

用于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"));
于 2012-11-30T08:24:25.270 回答
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 ,如果您只需要计数,这是一项重量级的工作。

于 2012-11-30T08:26:14.500 回答
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

于 2012-11-30T08:26:58.457 回答
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
"));

完结,祝你好运

于 2012-11-30T08:25:31.880 回答
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'];
}
于 2012-11-30T08:26:13.500 回答
0
SELECT COUNT(id) FROM table2

等等

于 2012-11-30T08:22:53.047 回答