删除query1具有的query2的选择值

时间:2016-01-25 17:52:41

标签: mysql sql database select

表PM: user1 | user2 |消息|时间戳| READ1

查询1:

SELECT count(message) as noOfReplies,user1 
FROM `pm` 
WHERE user2='Henry' and read1='' 
GROUP BY user1

输出:

output1

QUERY2:

SELECT count(message) as replies, 
if (user1='henry',user2,user1) as user,timestamp 
FROM `pm` 
WHERE read1='yes' and if(user1='henry',user1,user2) = 'henry' 
GROUP BY if(user1='henry',user2,user1)

输出:

output 2

我尝试做的是从query2的输出中删除coleen,因为该行已经从query1中显示

我尝试的是这样的:

SELECT count(message) as replies, if (user1='henry',user2,user1) as user
FROM `pm` 
WHERE read1='yes'and if(user1='henry',user1,user2) not in 
( 
    SELECT count(message) as noOfReplies,user1 
    FROM `pm` WHERE user2='Henry' and read1='' 
    GROUP BY  user1
)
and if(user1='henry',user1,user2) = 'henry'
GROUP BY  if(user1='henry',user2,user1) 

但我收到错误#1241 - 操作数应包含1列

1 个答案:

答案 0 :(得分:1)

您的错误来自NOT IN中的select必须只返回一列这一事实。要避免错误,请尝试以下操作:

SELECT count(message) as replies, if (user1='henry',user2,user1) as user
FROM `pm` 
WHERE read1='yes'and if(user1='henry',user1,user2) not in 
( 
    SELECT user1 -- here, ONE column
    FROM `pm` WHERE user2='Henry' and read1='' 
)
and if(user1='henry',user1,user2) = 'henry'
GROUP BY  if(user1='henry',user2,user1) 

但是在你的逻辑中有一些我不理解的东西。例如,如果您的if为false,则会检查user2是否在user1列表中......这是您想要的吗?