0

我有两张桌子。

用户

| id | name  |
| ---|-------|
| 1  | Jhon  |
| 2  | David |

刷卡

| id | swp_from | swp_to| first_swp| second_swp |
| ---|----------|-------|----------|------------|
| 1  | 1        | 2     | like     | pending    |
| 2  | 1        | 2     | like     | pending    |

我需要根据条件将这些加入到表swp_from中。swp_to

我的查询是这样的:

SELECT name, swp_to, first_swp FROM swipes
LEFT JOIN users ON users.id = swipes.swp_to // JOINING WITH swp_to TO MATCH FIRST WHERE CONDITION
WHERE 
(swipes.swp_from = :me AND ((swipes.first_swp NOT IN ('like', 'superlike')) OR (swipes.first_swp IN ('like', 'superlike') AND swipes.second_swp NOT IN ('like', 'superlike')))) // FIRST CONDITION
OR
(swipes.swp_to = :me AND swpipes.second_swp != 'pending') // FOR THIS SECOND CONDITION I NEED TO JOIN USERS TABLE USING swp_from AS WELL IN THIS SAME QUERY

正如上面查询中所解释的,我已经加入swp_to了该users表。但我还需要swp_from将第二个条件 inWHERE子句与users表连接起来。我怎样才能做到这一点?

简单来说,如果满足第一个 where 条件,我需要使用查询与users表连接。swp_to如果第二个条件(在 OR 之后)得到满足,那么我希望加入swp_from而不是swp_to. 这应该发生在每一行。PHP 条件逻辑解决方法也可以。

4

1 回答 1

1

条件应移至ON子句。

在 MySql中,CASE可以使用表达式来返回布尔表达式的结果(as10fortruefalse),如下所示:

SELECT u.name, s.swp_to, s.first_swp 
FROM swipes s LEFT JOIN users u
ON CASE (s.swp_from = :me AND ((s.first_swp NOT IN ('like', 'superlike')) OR (s.first_swp IN ('like', 'superlike') AND s.second_swp NOT IN ('like', 'superlike'))))
  WHEN 1 THEN u.id = s.swp_to
  WHEN 0 THEN u.id = s.swp_from AND (s.swp_to = :me AND s.second_swp <> 'pending')
END; 
于 2021-09-15T17:22:20.323 回答