我有两个表是这样的:如何使用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