9

我有一个函数,它接受一个在 where 子句中使用的参数

function(string x)-->现在这将创建一个 sql 查询,它给出

select colname from tablename where columnname=x;

现在我希望这个函数给所有行,即查询相当于

select colname from tablename;

当我通过 x="All" 时。

我想创建一个通用查询,当我通过“全部”时,它应该返回所有行,否则过滤我的结果。

4

9 回答 9

14

Just leave the where condition out.

If you really want it that complicated use

where columnname LIKE '%'

which will only filter nulls.

于 2012-07-27T06:22:18.363 回答
7
select colname from tablename 
where columnname=(case when @x ="All" then columnname
                  else  @x end)
于 2012-07-27T06:27:29.907 回答
4

尝试这个

select colname from tablename where 1=1

希望以上能奏效

于 2012-07-27T06:32:06.980 回答
2

where 1=1 对我有用,尽管使用了 where 子句,但所有记录都被选中。

你也可以试试

[any_column_name]=[column_name_in_LHL]

(LHL=左侧。)

请参阅我的答案以获取更多详细信息

于 2020-01-05T15:53:00.300 回答
1
SELECT * FROM table_name WHERE 1;
SELECT * FROM table_name WHERE 2;
SELECT * FROM table_name WHERE 1 = 1;
SELECT * FROM table_name WHERE true;

上述任何查询都将返回表中的所有记录。在我必须将条件作为参数传递的 Node.js 中,我像这样使用它。

const queryoptions = req.query.id!=null?{id : req.query.id } : true;
let query = 'SELECT * FROM table_name WHERE ?';
db.query(query,queryoptions,(err,result)=>{
res.send(result);
}
于 2019-02-06T10:13:15.457 回答
1

前段时间我遇到了同样的问题,这个解决方案对我有用

select colname from tablename where columnname=x or x = 'ALL'
于 2016-11-29T19:51:27.357 回答
0

目前还不清楚你的函数使用什么语言,但你必须在进入 sql 之前以某种方式解析“All”:

public void query(String param) {
  String value = "":
  switch (param) {
    case 'All':
      value = "*";
      break;
    default:
      value = param;
  }
  String sql = "select colname from tablename where colname="+value;
  //make the query
}
于 2012-07-27T06:24:21.013 回答
0

在您的代码中进行条件检查(假设 Java)WHERE仅在以下情况下附加子句x != 'All'

mySqlQuery = "SELECT colname FROM tablename" + 
                (x.equals("All") ? "" : "WHERE columnname = "+x);
于 2012-07-27T06:29:01.567 回答
0

If you have to allow 'ALL' to be passed through as the parameter value to your function, then you will need to put some manipulation code in your function to construct your SELECT statement accordingly. I.e. You can detect if the parameter has 'ALL' in it and then omit the WHERE clause from your SQL statement. If a value other than 'ALL' comes through, then you can include the WHERE clause along with the relevant filter value from the parameter.

An example of a piece of code to do this would be;

IF x = 'ALL'
THEN
   SELECT COLNAME FROM TABLENAME;
ELSE
   SELECT COLNAME FROM TABLENAME WHERE COLUMNNAME = X;
END IF;
于 2012-07-27T06:23:08.617 回答