SQL:处理多个 SELECT 条件?
我只是一个基本的 SQL 用户(现在是 mySQL+php)。我有带有多个输入(条件)的搜索框。
例如:
颜色:____
尺寸:____
价格:___
条件:___
折扣%:___
点击次数:___
等等,还有更多............
用户可以输入1个或多个字段。
结果也应该针对多个输入进行过滤。
那么,我该如何处理查询中的多个条件呢?
我很困惑如何编写查询(以以前的方式):从 _item_ WHERE color='silver' 中选择 * 和/或 .... ... ??????
????
请提供一个简单的示例。
I'm just an basic SQL user (mySQL+php now). I have search box with multiple input (conditions).
For example:
Color: ____
Size: ____
Price: ___
Condition: ___
Discount %: ___
Hit Count: ___
etc, many more ............
User may input 1 or more fileds.
Result should be filtered for multiple input also.
So, how can i handle this multiple conditions in Query?
I'm confusing how to write query (in former way):SELECT * FROM _item_ WHERE color='silver' AND/OR .... ... ?????
????
A simple sample please.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最简单的方法是使用一个基本查询,即使没有过滤条件,仍然返回结果:
这样您就可以根据用户界面中指定的内容轻松添加其他条件来进一步过滤结果。因此,如果有人说他们想要过滤颜色“银色”和条件“新”,我们只需将它们添加到查询的
WHERE
子句中:每个附加过滤条件只需添加基本查询末尾的
AND
。编辑:正如其他帖子中所指出的,这是一种幼稚的方法,您需要小心 SQL 注入,但最初的问题要求一个简单的示例,这就像我能想到的一样简单。
The easiest approach would be to have a base query, that even without filter criteria, still returns results:
this then allows you to easily add additional criteria to further filter your results, based on what was specified in the user interface. So, if someone says they want to filter on the color "silver" and the condition "new", we just add these to the
WHERE
clause of our query:each additional filter criteria can just be added with an
AND
to the end of the base query.edit: as pointed out in other posts, this is a naïve approach and you need to be careful of SQL injection, but the original question asked for a simple example and this was as simple as I could think of.
没有一种简单的解决方案。您可以根据参数从头开始创建动态 SQL,或者您可以为每个参数组合使用一些不同的 SP,或者您可以获取所有内容,然后在客户端进行过滤,或者...
但是要非常小心 SQL 注入。
我建议,在继续之前,您阅读类似 http://www.sommarskog.se/ 的内容dyn-search.html 和
http://www.sommarskog.se/dynamic_sql.html 其中提供了很多有关此问题的详细信息之类的事情。很长但值得。
There is no one simple solution. You could create dynamic SQL from scratch based on the parameters or you could use some a different SP for each combination of parameters or you could just get everything then filter in your client side or...
But be very careful about SQL injection.
I would suggest, before going any further, you read something like http://www.sommarskog.se/dyn-search.html and
http://www.sommarskog.se/dynamic_sql.html which give a lot of detail about this sort of thing. Long but worth it.
您可以使用 COALESCE 动态构造 WHERE 子句,如果提供的参数为 null,则将使用列值,因此您只需确保在适当的情况下传递 null:
请注意,这假设使用参数化查询,因此应该是漂亮的 SQL 注入证明。
You can use COALESCE to dynamically construct the WHERE clause, if the supplied parameter is null then column value will be used instead so you just need to ensure that you pass null where appropriate:
Note that this assumes the use of a parameterised query so should be pretty SQL Injection proof.