【问题标题】:how to use REGEXP in sql query如何在sql查询中使用REGEXP
【发布时间】:2017-01-26 08:46:49
【问题描述】:

我的表中有一个名为to_user 的列,其内容如下:

id     to_user

1.       1+2+3

2.         1

我的查询

select 
 * from notifications 
 where (type = 4 and to_user LIKE %+".$user_id."+%) 
 or (to_user REGEXP +?".$user_id."+? ) and status = 2

但它不起作用。

【问题讨论】:

标签: php mysql sql


【解决方案1】:

您应该将搜索字符串括在适当的引号中(如果不是您搜索条件的其他字符串,则删除 +)

"select * from notifications where (type = 4 and to_user LIKE '%".$user_id."%') 
    or (to_user REGEXP '".$user_id."' ) and status = 2" ;

由于你使用的是字符串,如果你需要一个精确的 macth 是 = i 而不是 like 并且不要使用正则表达式

【讨论】:

  • 你有一个错字;)请用'替换ì
  • 我认为这样做的好处是可以防止选择具有部分 id 的用户。如果你现在搜索用户 id 1,用户 id 215 也会被选中。
  • @Jerodev 我也为完全匹配添加了一个简短的建议
【解决方案2】:
$sql = "SELECT * 
FROM notifications 
WHERE (type = 4 and to_user 
LIKE '%" . $user_id . "%') 
OR (to_user REGEXP '\+" . $user_id . "\+' ) 
AND status = 2";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多