我有兩個表是這樣的:如何使用join子句來檢查行是否存在?
// 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
請編輯您的問題,幷包括你想要的輸出。 –
您是否嘗試加入Money_Paid mp ON p.amount IS NOT NULL AND mp.post_id = p.id AND mp.user_id =:user_id? –
@GordonLinoff我做到了。 – stack