dpfwhb7470 2013-11-06 06:30
浏览 60
已采纳

在SQL中使用Case

My sql table is like

posts-> id  postedby   timestamp
        1     1        12716826

comments-> id     postid     comby     tstamp      condition
            1       1           1         12716826      me
            2       1           1         12716826      all
            1       1           2         12716826      me
            1       1           3         12716826      all

My question is when i make a query to fetch all comments of post 1 . i want following condition

The comment with condition me should be visible to only me or post owner

I made a query like $myid=2; $postbyid=1;

$res=$db->query("SELECT * from comments where postid='$postbyid' 
                order by tstamp desc");
while ($row=$res->fetch_assoc())
{
if($row['comby']==$uid || $row['comby']=='$postbyid')
{
$data[]=$row;
}

else
{

if($row['condition']!='me')
{
$data[]=$row;
}
}
}

This may be wrong. Is there a way do this using SQL CASE?

like

 SELECT * from comments where postid='$postbyid' CASE WHEN comby='$myid' 
THEN SHOW ALL WHEN combyid='$postbyid' THEN SHOW ALL else dont 
show this row order by tstamp desc
  • 写回答

1条回答 默认 最新

  • dongliaoqiang8524 2013-11-06 07:23
    关注

    You just need to tweak your query conditions:

      SELECT *
        FROM comments
       WHERE postid = '$postbyid'
         AND comby IN ('$myid', '$postbyid')
    ORDER BY tstamp DESC
    

    I didn't get what you want with condition field, but from that query you can add another AND condition to satisfy the visibility restriction.

    Note that your code is vulnerable to SQL injection attacks, seems like that you're using mysqli module to work with database, so take a look at prepared statements section of mysqli manual: http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php

    Good luck!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行