2

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?

3
  • can you use a not equal to? for example if you have 6 tags and only want 1-5, the use usertag_tag !=6 Commented Dec 15, 2014 at 11:53
  • 3
    Use usertag_tag IN(1,2,3,4,5) which is standard SQL and will function like an OR chain. Commented Dec 15, 2014 at 11:53
  • The IN() operator. Commented Dec 15, 2014 at 11:54

7 Answers 7

3

you can use a simple version

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

Hope this helps

Sign up to request clarification or add additional context in comments.

Comments

0

You can use the IN statement:

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

Comments

0

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

Comments

0

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

Comments

0

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)

Comments

0

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.

Comments

0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.