[英]How do I use join clause to only check whether row exists?
我有兩個這樣的表:
// Posts
+----+---------+-----------------+----------+
| id | title | content | amount |
+----+---------+-----------------+----------+
| 1 | title1 | content1 | NULL |
| 2 | title2 | content2 | 1000 |
| 3 | title3 | content3 | 5000 |
| 4 | title4 | content4 | NULL |
| 5 | title5 | content5 | 2000 |
+----+---------+-----------------+----------+
// ^ NULL means that question is free
// Money_Paid
+----+---------+---------+
| id | user_id | post_id |
+----+---------+---------+
| 1 | 123 | 2 |
| 2 | 345 | 5 |
| 3 | 123 | 5 |
+----+---------+---------+
我正在嘗試做的所有事情:我的一些帖子不是免費的,而且任何人都希望看到他們應該支付費用。 現在,我需要一個查詢來檢查當前用戶是否已支付該帖子的費用? (僅適用於非免費帖子)
SELECT * FROM Posts p WHERE id = :post_id
LEFT JOIN Money_Paid mp ON p.amount IS NOT NULL AND ...
以下是一些示例 :( 基於當前表)
$stm->bindValue(":post_id", 2, PDO::PARAM_INT);
$stm->bindValue(":user_id", 123, PDO::PARAM_INT);
//=> TRUE (the user of '123' can see this post because he paid post's cost)
$stm->bindValue(":post_id", 2, PDO::PARAM_INT);
$stm->bindValue(":user_id", 345, PDO::PARAM_INT);
//=> FALSE (the user of '345' cannot see this post because he didn't pay post's cost)
$stm->bindValue(":post_id", 5, PDO::PARAM_INT);
$stm->bindValue(":user_id", 345, PDO::PARAM_INT);
//=> TRUE
我只需要查詢:我希望一列包含true
或false
(僅適用於非免費帖子),以告訴我當前用戶是否支付了當前帖子的費用。 換句話說:
Money_paid
表中有一行,其中user_id = :user_id
=> true
沒有任何行-> false
並非100%肯定我會理解您期望的結果,但是這是一種添加新列的方法,該列可以根據用戶是否付款而返回true或false:
select *,
case when mp.id is not null then 'true' else 'false' end paid
from Posts p
left join Money_Paid mp ON mp.post_id = p.id and mp.user_id = :user_id
where p.id = :post_id
查詢如下所示:
SELECT *
FROM Posts p
JOIN Money_Paid mp ON p.id = mp.post_id
WHERE mp.user_id = :user_id
AND p.id = :post_id
如果用戶已經為內容付費,則將返回該行。 如果用戶沒有為內容付費,則不會返回任何內容。
正如我評論的那樣,您可以嘗試(檢查聯接的位置)
SELECT * FROM Posts p
INNER JOIN Money_Paid mp ON p.amount IS NOT NULL AND
JOIN Money_Paid mp ON
mp.post_id = p.id AND p.amount IS NOT NULL AND mp.user_id = :user_id
WHERE
id = :post_id
另外,您可以列出所有列表。
SELECT * FROM Posts p
WHERE
p.amount IS NULL
UNION
SELECT * FROM Posts p
INNER JOIN Money_Paid mp ON
p.amount IS NOT NULL AND
mp.post_id = p.id AND
mp.user_id = :user_id
要么
SELECT * FROM Posts p
WHERE
p.amount IS NULL
OR p.id in (
SELECT post_id FROM Money_Paid mp
WHERE
p.amount IS NOT NULL AND
mp.user_id = :user_id
)
如果您想要的列將告訴您是否可以查看帖子或不嘗試這樣的操作(左聯接和if語句)
select
p.*,
if(p.amount is not null, if(mp.user_id is not null, 1, 0), 1) as canView
from Posts p
left join Money_Paid mp on mp.post_id = p.id and mp.user_id = :user_id;
如果canView列為1,則用戶可以查看帖子,否則無法查看。 您也可以檢查特定的帖子,只需在where p.id = :post_id
添加where p.id = :post_id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.