php mysql将多个相同的查询合并为一个

时间:2011-06-15 19:13:50

标签: php mysql

所以我的范围从1到40,

我必须使用它来执行来自同一个表和列的不同查询,但是来自不同的范围,如:

mysql_query("SELECT * FROM table WHERE column > 1 && column <= 15");
mysql_query("SELECT * FROM table WHERE column >=18 && column <= 30");
mysql_query("SELECT * FROM table WHERE column >= 35 && column <= 38");

我从这些查询中逐一获取不同操作的总行数......但是,我如何将这3个示例查询合并为1并获得相同的结果?

3 个答案:

答案 0 :(得分:5)

SELECT * FROM table 
WHERE (column > 1 AND column <= 15) 
OR (column >= 18 AND column <= 30) 
OR (column >= 35 AND column <= 38)

//编辑:OP想要计算每个条件的行数:

SELECT 
(SELECT COUNT(*) FROM table WHERE column > 1 AND column <= 15) AS count_1, 
(SELECT COUNT(*) FROM table WHERE column >= 18 AND column <= 30) AS count_2, 
(SELECT COUNT(*) FROM table WHERE column >= 35 AND column <= 38) AS count_3 
FROM table

count_1,count_2和count_3是每个条件的行数。

答案 1 :(得分:2)

重编,因为我误读了这个问题

如果你想要你可以做的所有行:

SELECT * FROM table WHERE (column > 1 AND column <= 15) OR
  (column >=18 AND column <= 30) OR
  (column >= 35 AND column <= 38)

但是,如果您只想要每个人的计数,那么这不是正确的方法。可以使用count(*)直接在MySQL中计算计数。即使您要进行三次单独的查询,最好使用count(*)而不是选择所有行(它使用更少的内存)。

话虽如此,您可以获得所有行的计数:

$query = "SELECT ".
      " (SELECT COUNT(*) FROM table WHERE column > 1 AND column <= 15) AS count_1,".
      " (SELECT COUNT(*) FROM table WHERE column >= 18 AND column <= 30) AS count_2,". 
      " (SELECT COUNT(*) FROM table WHERE column >= 35 AND column <= 38) AS count_3";

$res = mysql_query($query);
extract( mysql_fetch_assoc($res) );

echo "The counts are $count_1, $count_2, and $count_3";

extract函数将采用关联数组并为该数组中的每个项设置局部变量。我只是认为使用它比处理从mysql_fetch_assoc返回的数组更容易。

注意: @ fn -n首先发布了SQL,我只是将其格式化为PHP。我会以不同的方式写它,除了(s?)他已经以正确的方式做到了:)

答案 2 :(得分:0)

<击>

<击>
$query =    'SELECT * FROM table '.
            'WHERE (column > 1 && column <= 15) '.
            'OR (column >=18 && column <= 30) '.
            'OR (column >= 35 && column <= 38)';
mysql_query($query);

<击>