MySQL加入案例陈述

时间:2014-08-22 18:53:29

标签: php mysql sql case-statement

我在查询时遇到了一些麻烦。如果满足案例,我想加入表格。这是我正在使用的查询。我对这些案例陈述很新,所以非常感谢任何帮助!

      SELECT 
        conversation.c_id,
        conversation.user_one,
        conversation.user_two,
        users.name,
        users.lastName
      FROM `conversation` 

      CASE
        WHEN conversation.user_one = 1
        THEN
          INNER JOIN `users`
          ON conversation.two = users.id

        WHEN conversation.user_two = 1
        THEN
          INNER JOIN `users`
          ON conversation.user_one = users.id
      END CASE

      WHERE `user_one` = 1 OR `user_two` = 1

1 个答案:

答案 0 :(得分:4)

不要考虑整个内部联接,只在' on'连接中的子句。这应该有效(除非我有拼写错误):

  SELECT 
    conversation.c_id,
    conversation.user_one,
    conversation.user_two,
    users.name,
    users.lastName
  FROM `conversation` 
  INNER JOIN `users`
  on
  users.id =
  CASE
    WHEN conversation.user_one = 1
    THEN conversation.two 
    WHEN conversation.user_two = 1
    THEN conversation.user_one   
 END
 WHERE `user_one` = 1 OR `user_two` = 1

您还可以通过左键连接每个条件来实现类似的效果,然后在select语句中使用case语句来确定显示记录的两个表中的哪一个。