Php 当where子句的条件为false时,如何返回true?

Php 当where子句的条件为false时,如何返回true?,php,mysql,pdo,Php,Mysql,Pdo,我有两张这样的桌子: // Posts +----+---------+-----------------+----------+ | id | title | content | amount | +----+---------+-----------------+----------+ | 1 | title1 | content1 | NULL | | 2 | title2 | content2 | 1000 |

我有两张这样的桌子:

// 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       |
+----+---------+---------+
我想做的一切:我的一些帖子不是免费的,任何想看的人都应该付费。现在我需要一个查询来检查当前用户是否支付了该帖子的费用?(仅适用于非免费邮件)


以下是一些示例(基于当前表格)


我的问题是什么?当帖子空闲时,我的查询输出是
0
。(当帖子免费时,我需要
1

再说一遍。我需要
1
用于免费帖子和付费用户,而
0
用于未付费用户。用PHP像这样轻松地处理它

if ($result['paid'] == 1) {
    // show it
} elas {
   // doesn't show it
}

如何修复它?

我还没有测试过,但我认为如果用户已经付费或帖子是免费的,那么这将给出
$result['paid']>=1
,如果不是免费的,并且用户没有付费,那么这将给出
$result['paid']==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()
或等效函数来决定是否显示它。

我不确定此查询是否最佳,但它可以工作:

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

试试这个:

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)

只是好奇为什么你需要三个输出-为什么不直接询问用户是否可以看到帖子,是免费的还是付费的?@abracadver你是对的。但是我的查询对于未付费用户和免费帖子都返回
0
。我需要它返回
1
免费帖子。我该怎么做?要在php中轻松处理它:
if($result['paid']==1){//show it}else{//don show it}
我编辑了我的问题。这个查询不需要子选择或案例。您的查询想法很棒。。但实际上你的查询是不完整的。您的查询只是检查我是否应该向当前用户显示这样的帖子,而我的查询(在问题中)同时检查并获取帖子。
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
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)