Rails的SQL经常EX pressionSQL、Rails、pression、EX

2023-09-08 18:49:57 作者:大哥有钱就他娘的甩了你

我试图寻找该系列A0001的最大数量,A0002,A1234,A2351,等等的问题是,名单我在寻找的也有,如AG108939,E092357,AL399串, 22-30597,等等...

因此​​,基本上,我想在我的数据库中的一个最高值####。我用下面的查询:

  @max_draw = Drawing.where(drawing_number样?,A%)
 

这是工作,直到如AG309号开始的方式获得,因为它与A开始,但是有不同的格式比我期待的。

我猜想这应该是pretty的直线前进定期EX pressions,但我是新来这个,不知道如何正确地写这个查询与常规的前pression 。这里有一些事情我已经试过,只是返回nil:

  @max_draw = Drawing.where(drawing_number样?,/ A \ D + /)
 @max_draw = Drawing.where(drawing_number样?,/ A \ D + /)
 @max_draw = Drawing.where(drawing_number样?,A [0-9]%)
 

解决方案 sqlserver2005 express 64位 sqlserver2005安装图解

您做的不错!事情缺少的是 REGEXP 函数用于正则表达式中的查询:

所以,你的情况使用

  Drawing.where(drawing_number REGEXP?,A \ D {4})
#在{4}定义有必须正好4个号码,如果你需要改变
 

在SQL中使用' - 冒号,这是奇怪的,因为你正常启动正则表达式与 / - 反斜杠

I'm trying to search for the maximum number in the series A0001, A0002, A1234, A2351, etc... The problem is that the list I'm searching in also has strings such as AG108939, E092357, AL399, 22-30597, etc...

So basically, I want the Highest A#### value in my database. I was using the following query:

@max_draw = Drawing.where("drawing_number LIKE ?", "A%")

Which was working until numbers such as AG309 started getting in the way because it starts with an A, but has a different format than what I'm looking for.

I'm assuming this should be pretty straight forward with regular expressions, but I'm new to this and don't know how to correctly write this query with a regular expression. Here are some things I've tried that just return nil:

 @max_draw = Drawing.where("drawing_number LIKE ?", /A\d+/)
 @max_draw = Drawing.where("drawing_number LIKE ?", "/A\d+/")
 @max_draw = Drawing.where("drawing_number LIKE ?", "A[0-9]%")

解决方案

You did a good job! The thing missing was the REGEXP function which is used for regex in queries:

So in your case use

Drawing.where("drawing_number REGEXP ?", 'A\d{4}')
# the {4} defines that there have to be exactly 4 numbers, change if you need to

In SQL you use the '-colons, which is weird because you normally start regex with /-backslashes