简体   繁体   中英

Difference between “WHERE ” and “IN” in mysql

What is difference between:

SELECT * FROM news WHERE cat_id IN (1, 2, 6, 8);

and create a loop:

 foreach($cat as $key => $value){
    $sql = "SELECT * FROM news WHERE cat_id = $value['id'];
 }

The first example is far more efficient because only 1 sql query is run. The second example has x amount of queries, and is far slower.

I would say that you should never do it the second way and always the first way.

The first example runs only 1 query, while the second runs N queries.

Oh yeah, never do it the second way.

I think just for some circumstances, when you want to extract data from DB in exact order of input ids, you might want to use the second statement.

In this case, when you use the first query, the result might not in the order of input ids (1,2,6,8) if these ids are not in this order in DB. The first id that matches the DB will return result.

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