在SQL中使用IF / CASE调节

时间:2015-02-19 00:30:51

标签: mysql sql

我有一个关于如何在SQL中使用IF语句的问题,所以我有3个表

  • 用户
  • mechanics
  • 交流

每个表中的字段如下

 user        mechanics      exchanges
------      ----------      ---------
name         name           id_user
id_user      id_mecha       id_mecha 
                            message

我想使用类似以下条件的条件,如果他们user,我将选择mechanicmessage及其对应id的名称}匹配exchanges为其中每一个usermechanic

SELECT CASE  
         WHEN mechanics.id_mecha = exchanges.id_mecha  
            THEN  mechanics.name, exchanges.message
         WHEN users.id_user = exchanges.id_user 
            THEN users.name, exchanges.message
FROM users 
JOIN mechanics 
JOIN exchanges

3 个答案:

答案 0 :(得分:4)

JOIN将在机制和用户之间产生完整的交叉产品。这可能不是你想要的。您应该对每个表使用单个连接,然后将它们与UNION结合使用。

SELECT m.name, e.message
FROM mechanics AS m
JOIN exchanges AS e ON m.id_mecha = e.id_mecha

UNION

SELECT u.name, e.message
FROM users AS u
JOIN exchanges AS e ON m.id_user = e.id_user

答案 1 :(得分:0)

如果我理解正确,您需要END SELECT ON JOINSELECT CASE WHEN mechanics.id_mecha = exchanges.id_mecha THEN mechanics.name WHEN users.id_user = exchanges.id_user THEN users.name END, exchanges.message FROM users u JOIN mechanics m ON users.id_user = exchanges.id_user JOIN exchanges e ON mechanics.id_mecha = exchanges.id_mecha 需要{{1}},如下所示

{{1}}

答案 2 :(得分:0)

实际上你需要一个带有JOIN语句的case(假设一个特定的消息只能用于一个用户或一个特定的机制 - 而不是两个同时在一行中):< / p>

SELECT case 
       when e.id_user is null then m.name
       when e.id_mecha is null then u.name
       else null end,
       e.message
from exchanges e join users u on e.id_user=u.id_user
     join mechanics m on e.id_mecha=m.id_mecha