从mySQL表中排除结果

时间:2012-01-08 13:33:54

标签: mysql

我有一个表 t1 ,其中包含 t1.subgroup 列混合ID。有些是简单的数值,有些有前缀: a0

  

2,554,9844,a0433,4363,a0565 ......

实际上,像a0433和a0565这样的值实际上对应于另一个表中的433和565.

我需要编写一个查询,当我获得一组数字ID时,它会从t1的结果中排除某些值。

SELECT * FROM t1 WHERE t1.group = 2
AND t1.subgroup NOT IN(9844, 433, 565)

我该怎么做?

3 个答案:

答案 0 :(得分:2)

SELECT * FROM t1 WHERE t1.group = 2
AND 
REPLACE(t1.subgroup, 'a0', '') NOT IN (SELECT ThatValue) FROM AnotherTable)

但是,如果任何值为NULL,则会失败。所以

SELECT * 
FROM 
     t1 
WHERE 
    t1.group = 2
    AND 
    NOT EXISTS (SELECT * FROM AnotherTable A
               WHERE 
               REPLACE(t1.subgroup, 'a0', '') = A.ThatValue)

编辑:添加了REPLACE,删除了CONCAT

答案 1 :(得分:1)

SELECT [your fields] FROM t1 WHERE t1.group = 2
AND replace(t1.subgroup,'a0','') NOT IN(9844, 433, 565)

虽然表现可能不是最好的。它还假设mysql对此字符串执行了对字符串的int to int和int to string的转换,或者替换将需要进行转换。

答案 2 :(得分:0)

显然,您的列t1.subgroup是varchar或类似的(某些文本类型),因此您希望将查询编写为:

SELECT * FROM t1 WHERE t1.group = 2
AND t1.subgroup NOT IN('9844', '433', '565')