简体   繁体   English

在MySQL中使用带有变量的LIKE

[英]Using LIKE in MySQL with a variable

OK so I would like to get a match for a query of the database using a LIKE operator in my SQL statement. 好的,所以我想在我的SQL语句中使用LIKE运算符来获取数据库查询的匹配项。

I'm looking at a field that has a date and time in it, like this 我正在看一个有日期和时间的字段,就像这样

2012-04-27 12:00:00

I only want to compare the first part of the string, just the date bit, so I was using LIKE but I don't get any matches. 我只想比较字符串的第一部分,只比较日期位,所以我使用了LIKE,但我没有得到任何匹配。

Here's the code 这是代码

$colname_cruises = "-1";
if (isset($_GET['id'])) {
$colname_cruises = str_replace('-', ' ', $_GET['id']);
}

$colname_date = "-1";
if (isset($_GET['date'])) {
$colname_date = $_GET['date'];
}

$query_cruises = sprintf("SELECT * FROM cruises WHERE title = %s AND departs LIKE %s", GetSQLValueString($colname_cruises, "text"), GetSQLValueString($colname_date, "text"));
$cruises = mysql_query($query_cruises, $connection) or die(mysql_error());
$row_cruises = mysql_fetch_assoc($cruises);
$totalRows_cruises = mysql_num_rows($cruises);

I'm pretty certain just doing a LIKE %s isn't enough... what else can I add in here ? 我很确定只是做一个LIKE%s还不够......我还能在这里添加什么?

if you only want to compare the first part of the string, just the date then why dont you use MySQL DATE() which 如果你只想比较字符串的第一部分,只是日期,那么为什么不使用MySQL DATE()

Extracts the date part of the date or datetime expression expr 提取日期或日期时间表达式expr的日期部分

 SELECT DATE('2003-12-31 01:02:03');
   -> '2003-12-31'

For date comparison you can use between. 对于日期比较,您可以使用。 Try to use something like that: 尝试使用类似的东西:

departs between <date> and DATE_ADD(<date>,INTERVAL 1 DAY)

Please try 请试试

 "SELECT * FROM cruises WHERE title = '".$colname_cruises."' AND departs LIKE '".$colname_date."%'";

If you want to fetch record where departs value starting string containg this date then you have to use Like $str% . 如果你想获取记录,其中离开值的起始字符串包含此日期,那么你必须使用Like $str%

thanks 谢谢

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

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