[英]Checking certain row from a table which is referenced to another table?
我知道這個問題根本不會對我的要求有任何意義,但我的意思是.....為了使其更清楚,我將在例子中說明我的問題:
我有一個userpost
表,其中包含來自不同用戶的帖子。
userpost表:
+---------+--------+--------------+
| postId | userId | postMessage |
+---------+--------+--------------+
| 1 | 3 | someText |
| 2 | 5 | someText |
| 3 | 2 | sometext |
| 5 | 6 | someText |
+---------+--------+--------------+
( !記住 userId
被引用到 users
表)
我有另一個名為favorites
表,其中postId
是從userpost
表引用的:
收藏表:
+---------+--------+
| postId | userId |
+---------+--------+
| 1 | 5 |
| 3 | 2 |
+---------+--------+
我想要的是從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 |
+---------+--------+-------------+--------------+
我知道我在查詢中犯了錯誤:
(WHERE favorites.postId = 1 AND favorites.userId = 5)
這確實是真的。
我會給你一個我想要的例子:
讓我們說(userId = 5)
想要獲取所有用戶userpost
,我們必須得到以下結果:
+---------+--------+-------------+--------------+
| postId | userId | postMessage | isFavourited |
+---------+--------+-------------+--------------+
| 1 | 3 | someText | 1 |
| 2 | 5 | someText | 0 |
| 3 | 2 | someText | 0 |
| 5 | 3 | someText | 0 |
+---------+--------+-------------+--------------+
如果我理解你的要求,我想你可以做這樣的事情:
select up.*, case when f.postId is null then "0" else "1" end as isFavourited
from userpost up
left join favourites f on f.postId = up.postId and f.userId = up.userId
嘗試:
SELECT *,
postId IN
(SELECT postId FROM favourites WHERE userId = 5)
AS isFavourited
FROM userPost
您的查詢檢查是否存在用戶5收藏夾發布1的行; 而不是用戶5最喜歡在該行返回中選擇的帖子。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.