我有一个用户名数组作为用户:[Test1,Test2]。我必须遍历该数组,并且应该从表b中找到不匹配的用户名。我编写了如下查询:
def usersArray = []
def find
params.users.each{
find= sql.rows("select distinct name from table a,table b where a.id=b.id and b.name!=:n",[n:it])
if(find.size >0)
{
def usList = ["nm":find]
usersArray.push(usList);
}
}
从上述解决方案的结果中,即使匹配,我也可以看到测试1和测试2。如何更改查询以仅显示不匹配的用户?
答案 0 :(得分:0)
以下是您可能如何解决此问题的示例。假设您有一个名为User
的域类,并且要匹配一个名为name
的属性。
// given a list of user names
List users = ['Test1', 'Test2', 'Test3', 'Test4']
// find all the users that match those names, and collect the matched names into a List
List matched = User.findAll("from User as u where u.name in (:names)", [names: users]).collect { it.name }
// remove the matched names from the user list and arrive at an 'unmatched' names list
List unmatched = users.minus(matched)
这是写在我头上的内容,因此请原谅任何错别字或其他随机假设。
已更新 由于您似乎已开始使用SQL,因此您或许可以执行类似的操作
List users = ['Test1', 'Test2', 'Test3', 'Test4']
List placeholders = []
users.each { placeholders << '?' }
String select = "select distinct name from table a,table b where a.id=b.id and b.name in (${placeholders.join(',')})"
List matched = sql.rows(select, users)
List unmatched = users.minus(matched)
答案 1 :(得分:0)
另一种方法-计算与参数名称匹配的现有行,然后推送具有零的行(原谅错误的语法):
....
numberFound = sql.rows("select count(*)from table a where a.name=:n",[n:it])
if(numberFound = 0)
{
def usList = ["nm":find]
usersArray.push(usList);
}
...