简体   繁体   中英

mysql query using multiple OR statements

Is there a better way than this?

SELECT * FROM tagcloud 
WHERE (usertag_tag = 1 
OR usertag_tag = 2 
OR usertag_tag = 3    
OR usertag_tag = 4)

What if I want to add more tags to the query, do I keep adding OR statements?

you can use a simple version

 SELECT * FROM tagcloud 
WHERE usertag_tag in (1,2,3,4);

Hope this helps

您可以使用IN语句:

SELECT * FROM tagcloud WHERE user_tag IN(1,2,3,4)

类似于SELECT * FROM tagcloud在(1、2、3、4)中的usertag_tag。

You should prepare a list and make a select from it:

$tags = array( 1, 2, 3, 4 );
$query = "SELECT * FROM tagcloud WHERE usertag_tag IN (" . implode( ',', $tags ) . ")";

IN can be used but I guess the ids that you are inserting are dynamic (can be from another table) so you may use

 SELECT * FROM tagcloud 
 WHERE usertag_tag in (select id from the_other_table)

if not then this is okay

 SELECT * FROM tagcloud 
 WHERE usertag_tag in (1,2,3,4)

You could use an array like this,

$sql = "SELECT * FROM tagcloud WHERE user_tag IN ";  

$j = 6;

for($i = 0; $i< $j; $i++){
$queryArray[] .= "('". $i. "')";
}

$sql .= implode(',', $queryArray);

Just change j to your desired value.

Use MySQL IN

SELECT * FROM tagcloud 
WHERE (usertag_tag = 1 
OR usertag_tag = 2 
OR usertag_tag = 3    
OR usertag_tag = 4)

/* You are checking whether usertag_tag is either 1, 2, 3 OR 4*/

Is equivalent to:

SELECT * FROM tagcloud 
WHERE (usertag_tag IN (1, 2, 3, 4))
/* You are checking usertag_tag is one of the  values in the array given as 
array(1, 2, 3, 4)
If you want to add more values, just add elements to the array, that is it.
*/

Explanation:

If we are comparing single value, we use = .

If we need to find a rows with given field in one of the values (array of values), we use IN .

MySQL IN functions logically same as PHP's in_array()

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