我知道这个问题对我要问的问题根本没有任何意义,但是我的意思是…..为了更清楚,我将在示例中说明我的问题:
我有一个userpost表,其中包含来自不同用户的帖子.
userpost表:
+---------+--------+--------------+
| postId | userId | postMessage |
+---------+--------+--------------+
| 1 | 3 | someText |
| 2 | 5 | someText |
| 3 | 2 | sometext |
| 5 | 6 | someText |
+---------+--------+--------------+
(!记住userId被引用到用户表)
我还有一个名为“收藏夹”的表,其中从userpost表引用了postId:
收藏夹表:
+---------+--------+
| postId | userId |
+---------+--------+
| 1 | 5 |
| 3 | 2 |
+---------+--------+
我想要的是从userpost中获取所有数据,并检查某个特定的userpost是否已被(WHERE userId = 5)所青睐.
我尝试使用此查询,但这不是我想要的!
SELECT *,
(SELECT EXISTS( SELECT * FROM `favorites` INNER JOIN `userpost` on
favourites.postId = userpost.postId WHERE favorites.postId = 1
AND favorites.userId = 5)) AS isFavourited FROM userpost;
这是以下查询的结果:
+---------+--------+-------------+--------------+
| postId | userId | postMessage | isFavourited |
+---------+--------+-------------+--------------+
| 1 | 3 | someText | 1 |
| 2 | 5 | someText | 1 |
| 3 | 2 | someText | 1 |
| 5 | 3 | someText | 1 |
+---------+--------+-------------+--------------+
我知道我通过使用以下方式在查询中犯了错误:
(其中收藏夹.postId = 1和收藏夹.userId = 5)
确实返回true.
我会给你一个我想要的例子:
假设(userId = 5)要获取所有userpost,我们必须得到以下结果:
+---------+--------+-------------+--------------+
| postId | userId | postMessage | isFavourited |
+---------+--------+-------------+--------------+
| 1 | 3 | someText | 1 |
| 2 | 5 | someText | 0 |
| 3 | 2 | someText | 0 |
| 5 | 3 | someText | 0 |
+---------+--------+-------------+--------------+