我有以下数据库结构,我想从特定用户和月份中选择所有内容。但它会返回特定的用户数据,但是所有月份都会返回 我在此示例中选择的月份是2014-02或2014年2月
date |user | some more data |
----------------------------------------
2014-01-20 |user1 | more data | //will not be skipped
2014-02-01 |user1 | more data |
2014-02-01 |user2 | more data | //will be skipped
2014-02-02 |user1 | more data |
2014-05-02 |user1 | more data | //will not be skipped
我通过预准备语句函数调用以下查询。 LIKE运算符似乎不起作用。
$query = "SELECT * FROM table1 WHERE user = ? AND date LIKE ?"
$user = "user1"; //These 2 actually come from user input so:
$date = "2014-02%"; //$user = $username; $date = $y."-".$m."%";
//function that runs the prepared statement (simplified)
//this function works for all other queries.
$result = $database->runQuery($query, array($user, $date));
while($row = mysqli_fetch_array($result){
echo $row['date'];
echo $row['user'];
echo $row['some more data'];
echo "<br>";
}
打印
2014-01-20 user1 more data //this line should not be printed but it does.
2014-02-01 user1 more data
2014-02-02 user1 more data
2014-05-02 user1 more data //also should not be printed.
所以我的问题是我在LIKE运算符中做错了什么?
我的实际查询。
//The system holds phone call data.
//dcontext is a variable that decides in which column the user is found.
//in case of dcontext = outgoing calls
//clid = username + extensions
//src = users phone number
//dst = to phone number (this can be extension from another user in the system)
//which wont be registered double in this case.
//when dcontext = incomming calls
//clid and src = the caller ID/phone number from the person calling.
//dst = the users phone number.
//when dcontext = internal call transfer
//clid = username + extension
//src = users phone number
//dst = transfered number
"SELECT * FROM table WHERE
(dcontext = ? AND (clid = ? OR src = ? OR dst = ? OR dst = ?)) OR
(dcontext = ? AND dst = ?) OR
(dcontext = ? AND (clid = ? OR src = ?)) AND
date LIKE ?"
date type = DateTime
答案 0 :(得分:1)
请勿使用like
。使用WHERE user = ? and year(date) = ? and month(date) = ?
,假设数据是Date或DateTime类型,而不是varchar。
答案 1 :(得分:0)
我认为你应该CAST
将你的约会日期改为string
格式,所以请尝试:
SELECT * FROM table1 WHERE user = ? AND CAST(date as char) LIKE ?
或使用DATE_FORMAT
功能
SELECT * FROM table1 WHERE user = ? AND DATE_FORMAT(date, '%Y-%m-%d') LIKE ?
修改强>:
过滤日期部分的另一种方法是extract
他们的部分:
SELECT * FROM table1 WHERE user = ? AND EXTRACT(year FROM date) = ? AND EXTRACT(month from date) = ?
但是你必须将year
和month
作为单独的参数传递
<强> EDIT2 强>:
我将查询的一些元素放在大括号中,以确保您的AND
运算符正常工作
尝试使用此查询:
SELECT * FROM table WHERE
((dcontext = ? AND (clid = ? OR src = ? OR dst = ? OR dst = ?)) OR
(dcontext = ? AND dst = ?) OR
(? AND (clid = ? OR src = ?))) AND (EXTRACT(year FROM date) = ? AND
(EXTRACT(month FROM date) = ? )