SQL IN和NOT IN替代?

时间:2017-07-17 23:11:49

标签: sql

我正在尝试找到一种方法来优化我的后续SQL查询,这需要很长时间才能运行:

<?php
    $db = mysqli_connect("localhost", "root", "", "photos");
    $sql = "SELECT * FROM images ORDER BY id DESC";
    $result = mysqli_query($db, $sql);
    while ($row = mysqli_fetch_array($result)) {
        echo "<a href='uploads/".$row['image']."' data-caption='".$row['text']."'> ";
        echo "<img  id='img_div'  src='uploads/".$row['image']."'/>";
        //echo "<p id='img_div'>".$row['desc']."</p>";
        echo "</a>";
        echo"<p id='p_div'>Share</p>";
        echo "<a href='http://www.facebook.com/sharer/sharer.php?u=www.example.com/uploads/".$row['image']."'>
        <i id='share_div' class='fa fa-facebook fa-lg' aria-hidden='true'></i></a>";
        echo "<a id='tweet_div' href='http://www.twitter.com/share?text=Check out this image from &quot;Quotin&quot;!&url=http://www.eample.com/uploads/".$row['image']."'&via=_Quotin_'>Tweet</a>";
    }
?>

我可以用另一个简单的查询替换它吗?

2 个答案:

答案 0 :(得分:1)

我将此逻辑移动到子查询中,如下所示:

select s.StaffID 
from StaffID as s inner join (
    Select StaffID
    From Schedule
    where
        AccountID=@AccountID and
        Date Between DATEADD(day, -90, @Today) and @Today and
    group by StaffID
    having max(case when Status=2 then 2 else 1 end) = 1
) as t
on (s.StaffID = t.StaffID)

因此,having中的条件会过滤掉过去90天内状态== 2的成员

答案 1 :(得分:1)

您可以使用聚合来组合两个表达式:

s.staffid in
(
  select staffid 
  from schedule
  where accountid = @accountid
    and date between dateadd(day, -90, @today) and @today 
  group by staffid  
  having count(case when status <> 2 then 1 end) > 0
     and count(case when status = 2 then 1 end) = 0
)