简体   繁体   English

使用多个SELECT语句来缩小结果范围

[英]Using multiple SELECT statements to narrow results

I have a database with some properties that have been sold. 我有一个包含一些已售出属性的数据库。 They each have a date associated with it which is what I need to use to narrow the search results. 它们每个都有一个与之关联的日期,这是我需要用来缩小搜索结果范围的日期。

Basically I have a query: 基本上我有一个查询:

$query = "SELECT * from newsales WHERE city = '".$_GET['location']."'";

And what I need to do is, from the results returned from the above query, I need to further narrow it down to be within the past 90 days. 我需要做的是,根据上述查询返回的结果,我需要将其范围进一步缩小到过去90天内。

So it'll find the city, and then it needs to ONLY get the ones from the last 90 days. 因此它将找到城市,然后只需要获取最近90天内的城市。 How do I combine SELECT statements to narrow the results down? 如何结合SELECT语句来缩小结果范围?

Thanks! 谢谢!

You could use the SQL AND operator. 您可以使用SQL AND运算符。

Doc: http://dev.mysql.com/doc/refman/5.1/en/logical-operators.html Doc: http : //dev.mysql.com/doc/refman/5.1/en/logical-operators.html

Your query would be than: 您的查询将是:

$query = "SELECT * from newsales WHERE city = '".$_GET['location']."' AND date > '".$oldestdate."';

Set $date to the oldes date, in your case 90 days before today. 在您的情况下,将$date设置$date旧日期,即今天之前的90天。 According to your dateformat in your mysql database you have to calculate this in a timestamp or datetime. 根据您在mysql数据库中的dateformat,您必须在一个时间戳或datetime中进行计算。

You don't need to combine SELECT statements, just make a more complex WHERE clause using the boolean AND operator: 您不需要合并SELECT语句,只需使用布尔AND运算符创建一个更复杂的WHERE子句:

$query = "
    SELECT * 
    FROM newsales 
    WHERE 
        city = '".$_GET['location']."'
        AND date > '".$oldestdate."'
";

I'd advise you to read up on SQL injection as well - if you use $_GET directly like that, someone can come to your website and basically type in any SQL statement they want. 我建议您也阅读SQL注入 -如果您这样直接使用$_GET ,则有人可以访问您的网站并基本上输入他们想要的任何SQL语句。

The easiest way, assuming you are using mysqli_* functions (which have replaced the mysql_* functions but can be used mostly interchangeably) is mysqli_real_escape_string() , eg city = '" . mysqli_real_escape_string($_GET['location']) . "' . 假设您正在使用mysqli_*函数(已取代mysql_*函数,但可以互换使用mysqli_real_escape_string() ,最简单的方法是mysqli_real_escape_string() ,例如city = '" . mysqli_real_escape_string($_GET['location']) . "'

Combining results of multiple SELECT statements means you need to use UNION. 合并多个SELECT语句的结果意味着您需要使用UNION。 Please see this : http://dev.mysql.com/doc/refman/5.0/en/union.html 请参见: http : //dev.mysql.com/doc/refman/5.0/en/union.html

(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);

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

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