选择何时在2列中的任何一列中不存在值

时间:2012-08-29 19:47:05

标签: mysql

我有两个字段emailaddlEmail。如果给定的电子邮件地址不在任何一个字段中,我需要一个仅选择记录的选择。

尝试将NOT IN用于两列(返回:Cardinality violation: 1241 Operand should contain 2 column(s):

SELECT WebUsername, 
  WebPassword, 
  Active, 
  Email, 
  AddlEmail, 
  ShowYear 
FROM Exhibitors e 
WHERE e.Active = '-1' 
AND e.ShowYear = 2013 
AND (e.Email, e.AddlEmail) NOT IN ('test@test.com', 'test2@test.com')"

我尝试过AND和OR,但由于显而易见的原因,它们无法正常工作。

为了试图彻底:

$emails = "'email@email.com', 'email2@email.com'";
// example table data for 2 fields in question
Row | Email              |   AddlEmail
1   | email@email.com    |   email3@email.com
2   | email4@email.com   |   email2@email.com
3   | email5@email.com   |   null
4   | email6@email.com   |   email7@email.com

查询应该只返回第3行和第4行。

感谢您查看,如果您需要进一步说明,请与我们联系。

克里斯

编辑: 样本表回应发布的答案:

CREATE TABLE `doubleSelect` (
  `Email` varchar(255) DEFAULT NULL,
  `AddlEmail` varchar(255) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `doubleSelect` (`Email`, `AddlEmail`) VALUES
  ('email@email.com', 'email2@email.com'),
  ('email2@email.com', 'email3@email.com'),
  ('email4@email.com', 'email5@email.com'),
  ('email6@email.com', 'email@email.com'),
  (NULL, 'email@email.com'),
  ('email2@email.com', NULL);

示例查询(不返回最后一行,它应该):

SELECT *
  FROM `doubleSelect`
  WHERE Email NOT
  IN (
    'email@email.com'
  )
  AND AddlEmail NOT
  IN (
    'email@email.com'
  )

2 个答案:

答案 0 :(得分:6)

简单

AND e.Email NOT IN ('test@test.com', 'test2@test.com') 
AND e.AddlEmail NOT IN ('test@test.com', 'test2@test.com') 

包括NULL值:

SELECT *
FROM `doubleSelect`
WHERE (Email IS NULL or Email NOT IN ('email@email.com'))
      AND (AddlEmail IS NULL or AddlEmail NOT IN ('email@email.com'))

答案 1 :(得分:2)

试试这个

select * 
from Exhibitors 
where (email is null or email not in('email@email.com', 'email2@email.com'))  
and   (addlEmail is null or addlEmail not in ('email@email.com', 'email2@email.com'))