WHERE子句中的Mysql和if / else语句

时间:2015-12-16 18:24:14

标签: mysql

我有这个SQL选择查询

SELECT * 
FROM bots 
WHERE id NOT IN (select botid 
                 from messages 
                 where messages.recipient = :recipient) 
limit 1

我需要做类似的事情:

SELECT * 
FROM bots 
[if isset(recipient = $recipient AND sender = $sender)] 
  WHERE id IN (select botid 
               from messages 
               where messages.recipient = :recipient and sender = :sender) 
else 
  WHERE id NOT IN (select botid 
                   from messages 
                   where messages.recipient = :recipient) 
limit 1

[] - 伪代码

如何进行此查询?

Bots表:

-------------------------------------------------------
| id       |  auth_token   |  messages_today  | vkid  |
-------------------------------------------------------
| 1       |  token   |                    0   | 2323  |
-------------------------------------------------------
| 2       |  token   |                     0  | 2343  |
-------------------------------------------------------

消息表:

-----------------------------------------------------------
| id       |  recipient   |  sender  | botid  | messageid |
-----------------------------------------------------------
| 1        |  12          |        1  |     1  |      3322 |
-----------------------------------------------------------
| 2        |  12          |        2  |     2  |    332123 |
-----------------------------------------------------------
| 3        |  13          |        1  |     1  |    332123 |
-----------------------------------------------------------

1 个答案:

答案 0 :(得分:1)

使用外连接

  • 从机器人表中返回所有机器人
  • 和来自匹配的消息talbe的数据
  • 但是我们消除了仅返回机器人的匹配数据 如果该特定机器人不存在提供收件人和发件人的邮件

返回所有机器人

Select * from bots B
LEFT JOIN messages M
  on M.BotID = B.ID
 and M.Sender = $sender
 and M.Recipient = $Recipient
Where M.BotID is null