我需要选择一个不等于某个语句的值本身.
就像是
SELECT * FROM table WHERE * != "qwerty"
Run Code Online (Sandbox Code Playgroud)
但不喜欢
SELECT * FROM table WHERE column_name != "qwerty"
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
我有一张桌子
1 2 3 4 5 6 7 8 9 10 11 ... ...
1 a b c d t h v h d t y ... ...
2 g t 5 s h r q q q q q ... ...
... ...
... ...
Run Code Online (Sandbox Code Playgroud)
我需要选择不等于"q"的每个值
我可以做得像
SELECT * WHERE 1 != q AND 2 != q AND 3 != q ...
Run Code Online (Sandbox Code Playgroud)
但是我有很多专栏
试试这个:
SELECT * FROM table WHERE "qwerty" NOT IN (column1,column2,column3,column4,etc)
Run Code Online (Sandbox Code Playgroud)
另一个例子:
-- this...
SELECT 'HELLO!' FROM tblx
WHERE 'JOHN' NOT IN (col1,col2,col3);
-- ...is semantically equivalent to:
SELECT 'HELLO!' FROM tblx
WHERE 'JOHN' <> col1
AND 'JOHN' <> col2
AND 'JOHN' <> col3;
Run Code Online (Sandbox Code Playgroud)
数据源:
create table tblx(col1 text,col2 text,col3 text);
insert into tblx values
('GEORGE','PAUL','RINGO'),
('GEORGE','JOHN','RINGO');
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Postgresql,则可以为列创建快捷方式:
select *
from
(
select
row(tblx.*)::text AS colsAsText,
translate(row(tblx.*)::text,'()','{}')::text[]
as colsAsArray
from tblx
) x
where 'JOHN' <> ALL(colsAsArray)
Run Code Online (Sandbox Code Playgroud)
现场测试:http://www.sqlfiddle.com/#!1/8de35/2
Postgres可以从数组中创建行,'JOHN' <> ALL相当于::
where 'JOHN' NOT IN (SELECT unnest(colsAsArray))
Run Code Online (Sandbox Code Playgroud)
现场测试:http://www.sqlfiddle.com/#!1/8de35/6
如果您真正想要实现上述目标,那么如果您使用全文搜索,搜索会更好
对于MySQL:
select
@columns := group_concat(column_name)
from information_schema.columns
where table_name = 'tblx'
group by table_name;
set @dynStmt :=
concat('select * from tblx where ? NOT IN (', @columns ,')');
select @dynStmt;
prepare stmt from @dynStmt;
set @filter := 'JOHN';
execute stmt using @filter;
deallocate prepare stmt;
Run Code Online (Sandbox Code Playgroud)
现场测试:http://www.sqlfiddle.com/#!2/ 8de35/ 49
| 归档时间: |
|
| 查看次数: |
1506 次 |
| 最近记录: |