简体   繁体   English

在唯一的php mysql查询上限制1?

[英]limit 1 on unique php mysql queries?

I was curious, in one doc i read it suggest using limit 1 on all queries if available including indexed and unique columns. 我很好奇,我读过一篇文档,建议对所有查询(包括索引列和唯一列)使用限制1。 Does writing limit 1 actually help queries when using a WHERE uniqueCol = val; 使用WHERE uniqueCol = val时,写限制1实际上是否对查询有帮助? ?

No, adding a 'limit 1' doesn't help speed your code up in those cases. 不,在这些情况下,添加“限制1”并不能帮助您加快代码的速度。 Instead, the usual reason why people are doing it, is instead as a 'protection' factor. 相反,人们这样做的通常原因是作为“保护”因素。 There are two situations where this can help you: 在两种情况下可以为您提供帮助:

  • Sometimes, depending upon your database design, you may THINK that there is only 1 result, but if the column you are selecting upon isn't actually a unique column, for some strange reason, then you might get two results back if the database integrity hasn't been kept. 有时,根据您的数据库设计,您可能会认为只有1个结果,但是如果您选择的列实际上不是唯一列,则出于某些奇怪的原因,如果数据库完整性,您可能会得到两个结果尚未保留。 I've seen programmers therefore use limit 1 in such cases, just to ensure that no matter what, they only get 1 result back when they are only expecting 1 result back, and therefore, it doesn't cause the code to fail. 我已经看到程序员因此在这种情况下使用限制1,只是为了确保无论如何,当他们只期望返回1个结果时,它们只能返回1个结果,因此,不会导致代码失败。

  • And security. 和安全性。 I've also seen people preach the idea of putting a limit 1 in your queries, to make it harder for SQL injection attacks to be very effective. 我还看到人们鼓吹在查询中添加限制1的想法,以使SQL注入攻击更加有效。 The idea being, that if someone does manage to do SQL injection, that they will only get '1 result' worth. 这个想法是,如果有人确实进行了SQL注入,那么他们只会得到“ 1结果”的价值。 Now the problem with this, is that in practice, this rarely works, since many SQL injection attacks end up ignoring the 'rest of the line' of data. 现在的问题是,在实践中,这很少起作用,因为许多SQL注入攻击最终都忽略了数据的“其余部分”。

So, in the end? 那么,到底呢? It certainly doesn't hurt you to put it in there. 将其放入其中肯定不会伤害您。 But there isn't really a solid reason why you should always do it. 但是,您确实应该始终这样做的确无确凿的理由。 And in fact, I rarely do it myself, just because the benefits you might convince yourself of, are rather minimal. 实际上,我很少自己做,只是因为您可能会说服自己的利益是微不足道的。

没有。

否:没有必要将单例集限制为具有一个元素。

It won't really offer much benefit in your case. 在您的情况下,它实际上不会提供太多好处。

You may find this previous discussion of interest Does adding 'LIMIT 1' to MySQL queries make them faster when you know there will only be 1 result? 您可能会发现前面的讨论很有趣, 当您知道只有1个结果时,是否在MySQL查询中添加“ LIMIT 1”会使它们更快?

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

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