我需要选择一个不等于某个语句的值本身。
有点像
SELECT * FROM table WHERE * != "qwerty"
但不喜欢
SELECT * FROM table WHERE column_name != "qwerty"
我该怎么做?
我有一张 table
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 ... ...
... ...
... ...
我需要选择每个不等于“q”的值
我可以这样做
SELECT * WHERE 1 != q AND 2 != q AND 3 != q ...
但是我的列太多了
最佳答案
试试这个:
SELECT * FROM table WHERE "qwerty" NOT IN (column1,column2,column3,column4,etc)
另一个例子:
-- 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;
数据来源:
create table tblx(col1 text,col2 text,col3 text);
insert into tblx values
('GEORGE','PAUL','RINGO'),
('GEORGE','JOHN','RINGO');
如果您使用的是 Postgresql,您可以为列创建一个快捷方式:
select *
from
(
select
row(tblx.*)::text AS colsAsText,
translate(row(tblx.*)::text,'()','{}')::text[]
as colsAsArray
from tblx
) x
where 'JOHN' <> ALL(colsAsArray)
现场测试:http://www.sqlfiddle.com/#!1/8de35/2
Postgres 可以从数组中生成行,'JOHN' <> ALL
相当于::
where 'JOHN' NOT IN (SELECT unnest(colsAsArray))
现场测试:http://www.sqlfiddle.com/#!1/8de35/6
如果以上确实是你想要实现的,如果你使用全文搜索,搜索会好得多
- PostgreSQL:http://www.postgresql.org/docs/9.1/static/textsearch.html
- SQL 服务器:http://msdn.microsoft.com/en-us/library/ms142571.aspx
- MySQL:http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
对于 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;
关于mysql - 如何选择每列都不匹配值的所有行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10468956/