加入同一个表的两个查询

时间:2014-10-18 12:15:09

标签: mysql

  

我想加入以下有意义的查询结果

SELECT `idCHAT`,`USER_NAME`,`TEXT`,`CURRENT_DATE_TIME`,`CHAT_COUNTERPARTY` FROM chat where USER_NAME='user1' group by `CHAT_COUNTERPARTY` ORDER BY `chat`.`CURRENT_DATE_TIME` DESC 

SELECT `idCHAT`,`USER_NAME`,`TEXT`,`CURRENT_DATE_TIME`,`CHAT_COUNTERPARTY` FROM chat where CHAT_COUNTERPARTY='user1' group by `USER_NAME` ORDER BY `chat`.`CURRENT_DATE_TIME` DESC
  

两个结果的UNION之后的结果

 idCHAT     USER_NAME   TEXT    CURRENT_DATE_TIME Descending    CHAT_COUNTERPARTY   
 6  user1   helSSSSSSlooooo     2014-10-17 20:45:22     user3
 4  user3   helSSSSSSlooooo     2014-10-17 20:44:00     user1
 3  user2   helSSSSSSlooooo     2014-10-17 20:43:59     user1
 1  user1   helSSSSSSlooooo     2014-10-17 20:40:41     user2
  

但我只想从表中获得idCHAT 6& 3因为user3& user2是user1的CHAT_COUNTERPARTY

2 个答案:

答案 0 :(得分:1)

select `idCHAT`,`USER_NAME`,`TEXT`,`CURRENT_DATE_TIME`,`CHAT_COUNTERPARTY`, if(USER_NAME='user1',`CHAT_COUNTERPARTY`,`USER_NAME`)as party from(SELECT `idCHAT`,`USER_NAME`,`TEXT`,`CURRENT_DATE_TIME`,`CHAT_COUNTERPARTY` FROM chat where USER_NAME='".$user."' group by `CHAT_COUNTERPARTY` UNION (SELECT `idCHAT`,`USER_NAME`,`TEXT`,`CURRENT_DATE_TIME`,`CHAT_COUNTERPARTY` FROM chat where CHAT_COUNTERPARTY='user1' group by `USER_NAME`) ORDER BY `CURRENT_DATE_TIME` DESC)res group by party order by `CURRENT_DATE_TIME` desc

答案 1 :(得分:0)

使用union关键字

SELECT `idCHAT`,`USER_NAME`,`TEXT`,`CURRENT_DATE_TIME`,`CHAT_COUNTERPARTY` 
FROM chat 
where USER_NAME='user1' 
group by `CHAT_COUNTERPARTY` 
UNION
(SELECT `idCHAT`,`USER_NAME`,`TEXT`,`CURRENT_DATE_TIME`,`CHAT_COUNTERPARTY` 
FROM chat 
where CHAT_COUNTERPARTY='user1' 
group by `USER_NAME`)
ORDER BY `CURRENT_DATE_TIME` DESC