简体   繁体   English

mysql中“ WHERE”和“ IN”之间的区别

[英]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. 第一个示例效率更高,因为仅运行了一个sql查询。 The second example has x amount of queries, and is far slower. 第二个示例的查询数量为x,并且速度慢得多。

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. 第一个示例仅运行1个查询,第二个示例运行N个查询。

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. 我认为仅在某些情况下,当您想输入ID的确切顺序从数据库中提取数据时,可能要使用第二条语句。

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. 在这种情况下,当您使用第一个查询时,如果这些ID在数据库中不是按此ID顺序排列,则结果可能不按输入ID(1、2、6、8)排列。 The first id that matches the DB will return result. 与数据库匹配的第一个ID将返回结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM