我有两张这样的表:
// 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
}
我该如何解决?
答案 0 :(得分:2)
我还没有通过测试,但我认为如果用户付费或帖子免费,我会$result['paid'] >= 1
,如果免费且用户没有&#{1}},则会$result['paid'] == 0
39;付了钱:
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)
然后使用数据库API中的num_rows()
或等效函数来决定是否显示它。
答案 1 :(得分:0)
我不确定这个查询是最好的,但它确实有效:
select *,
case when p.amount is null then '1'
else (select count(1)
from Money_paid mp
where mp.post_id = p.id and mp.user_id = :user_id limit 1)
end paid
from Posts p
where p.id = :post_id
对付付费用和免费帖子的用户,$result['paid']
1
为0
。对于无偿用户,它将是AddFriendPush
。
答案 2 :(得分:0)
试试这个:
select count(*) from ( select * from Posts p innerjoin Money_Paid mp on p.id=mp.post_id ) where id=:post_id and ( amount is null or user_id=:user_id)