如何选择每列不匹配值的所有行?

时间:2012-05-06 07:37:34

标签: mysql sql

我需要选择一个不等于某个语句的值本身。

这样的东西
SELECT * FROM table WHERE * != "qwerty"

但不喜欢

SELECT * FROM table WHERE column_name != "qwerty"

我该怎么做?

我有一张像

这样的表格
       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 ...

但我有toomany专栏

3 个答案:

答案 0 :(得分:7)

试试这个:

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


如果您真正想要实现上述目标,那么如果您使用全文搜索

,搜索会更好

对于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; 

实时测试:http://www.sqlfiddle.com/#!2/8de35/49

答案 1 :(得分:3)

这将为您提供所需的表达式。

select GROUP_CONCAT(COLUMN_NAME SEPARATOR ' != ''q'' AND ') as Exp
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'YourTable'

也许你可以在一些动态SQL中使用它,或者将字符串复制到真正的查询中。

答案 2 :(得分:0)

也许你可以试试SHOW COLUMNS

SHOW COLUMNS FROM SomeTable

这将返回所有列信息。

示例:

    [Field] => id
    [Type] => int(7)
    [Null] =>  
    [Key] => PRI
    [Default] =>
    [Extra] => auto_increment

然后,您可以使用 Michael Buen 的答案来获取您想要的值:

SELECT * FROM table WHERE "qwerty" NOT IN (columnName1,columnName2,columnName3,columnName4,etc)
相关问题