我有两个这样的表:
// 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 *,
(select count(1) from Money_paid mp where p.amount is not null and mp.post_id = p.id and mp.user_id = :user_id) paid
from Posts p
where p.id = :post_id
以下是一些示例:(基于当前表格)
$stm->bindValue(":post_id", 2, PDO::PARAM_INT);
$stm->bindValue(":user_id", 123, PDO::PARAM_INT);
// paid column => 1 (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);
// paid column => 0 (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);
// paid column => 1
我的问题是什么?当帖子免费时,我的查询输出为 0
。 (当帖子免费时我需要 1
)。
1
,对于非付费用户,我需要 0
。像这样通过 PHP 轻松处理它
if ($result['paid'] == 1) {
// show it
} elas {
// doesn't show it
}
如何修复它?
最佳答案
我还没有测试过,但我认为如果用户已付费或帖子免费或 $result['paid'] 这将给出
如果它不是免费的并且用户尚未付费:$result['paid'] >= 1
'] == 0
SELECT COUNT(*) AS paid FROM Post p, Money_paid mp
WHERE p.amount IS NULL OR (mp.post_id = p.id AND mp.user_id = :user_id)
简而言之,if($result['paid'] == 0)
不显示,或者如果您喜欢 if($result['paid'] >= 1)
确实显示。
根据您的评论获取帖子数据:
SELECT p.title, p.content FROM Post p, Money_paid mp
WHERE p.amount IS NULL OR (mp.post_id = p.id AND mp.user_id = :user_id)
然后使用 DB API 中的 num_rows()
或等效函数来决定是否显示它。
关于php - 当where子句的条件为假时,如何返回true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36585463/