简体   繁体   中英

php mysql merge multiple same queries into one

So i have some range from 1 to 40,

which i have to use in order execute different queries from the same table and column but from a different range like:

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");

i get the total rows from these queries one by one for different actions... but how can i combine these 3 for example queries into 1 and get the same result?

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

// EDIT: OP Wants to Count number of rows for each condition:

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, and count_3 are the numbers of rows for each condition.

Heavily edited because I misread the question

If you want all the rows you could just do:

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

However, if you just want the count for each, that is not the right way to go about it. The count can be calculated directly in MySQL using count(*) . Even if you were to do three separate queries it would be better to use count(*) over selecting all the rows (it used much less memory).

With that said, you can get the count for all the rows like this:

$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";

The extract function will take an associative array and set local variables for each item in that array. I just figured it would be easier to use than dealing with the array returned from mysql_fetch_assoc .

Note: @fn-n posted the SQL first, I just formatted it into PHP. I'd write it a different way except (s?)he already did it the right way :)

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

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