简体   繁体   English

将条件添加到mysql查询并再次获取

[英]Adding condition to mysql query and fetch again

I have 3 queries which I run which are nearly identical, the latter two have an AND condition. 我有3个查询,它们几乎是相同的,后两个查询是AND条件。

Main query: 主要查询:

$mess = $mysqli->prepare("SELECT * from ( SELECT cm.id ,cm.userid,cm.message,cm.voteup,cm.votedown,cm.date
                        FROM chat_messages cm 
                        INNER JOIN members m  ON m.id =cm.userid
                        INNER JOIN chat_settings cs ON cs.id = cm.room_id 
                        WHERE cm.setting_id = ?          
                        ORDER BY cm.date DESC LIMIT 30 ) ddd
                        ORDER BY date ASC ");
$mess->bind_param("i", $room);                              
$mess->execute();
$mess->store_result();

$mess->bind_result($chatid,$chat_userid,$message,$voteup,$votedown,$date);
while($row = $mess->fetch()){
    //im fetching here in my <div class='div1' >
}

Then, in the second div I have to add an AND condition: 然后,在第二个div我必须添加一个AND条件:

$mess2 = $mysqli->prepare("SELECT * from ( SELECT cm.id ,cm.userid,cm.message,cm.voteup,cm.votedown,cm.date
                        FROM chat_messages cm 
                        INNER JOIN members m  ON m.id =cm.userid
                        INNER JOIN chat_settings cs ON cs.id = cm.room_id
                        WHERE cm.setting_id = ?    AND voteup - votedown >= 5      
                        ORDER BY cm.date DESC LIMIT 30 ) ddd
                            ORDER BY date ASC ");
$mess2->bind_param("i", $room);                              
$mess2->execute();
$mess2->store_result();

$mess2->bind_result($chatid,$chat_userid,$message,$voteup,$votedown,$date);
while($row2 = $mess2->fetch()){
    //im fetching here in my <div class='div2' >
}

Lastly, in the third div I have a slightly different AND condition: 最后,在第三个div我的AND条件略有不同:

$mess3 = $mysqli->prepare("SELECT * from ( SELECT cm.id ,cm.userid,cm.message,cm.voteup,cm.votedown,cm.date
                        FROM chat_messages cm 
                        INNER JOIN members m  ON m.id =cm.userid
                        INNER JOIN chat_settings cs ON cs.id = cm.room_id 
                        WHERE cm.setting_id = ?    AND votedown - voteup >= 5      
                        ORDER BY cm.date DESC LIMIT 30 ) ddd
                            ORDER BY date ASC ");
$mess3->bind_param("i", $room);                              
$mess3->execute();
$mess3->store_result();

$mess3->bind_result($chatid,$chat_userid,$message,$voteup,$votedown,$date);
while($row3 = $mess3->fetch()){
    //im fetching here in my <div class='div3' >
}

Everything works BUT doing this near-same query seems clumsy. 一切正常, 执行此近乎相同的查询似乎很笨拙。 Is it possible to construct the same thing with only one query? 是否只用一个查询就可以构造相同的东西? I have used $mess->data_seek(0); 我已经使用$mess->data_seek(0); but its not helping because I didn't add my condition to the query. 但它没有帮助,因为我没有将条件添加到查询中。

Just go for PhP to filter your data instead of triple query your database. 只需使用PhP即可过滤数据,而不是对数据库进行三重查询。 In this case you can figure out to go for this solution because you call 3 times your query with the same parameter : 在这种情况下,您可以考虑采用此解决方案,因为您使用相同的参数调用了3次查询:

    $mess3  =   $mysqli->prepare("  SELECT    * 
                                    FROM      ( SELECT  cm.id ,
                                                        cm.userid,
                                                        cm.message,
                                                        cm.voteup,
                                                        cm.votedown,
                                                        cm.date
                                                FROM        chat_messages cm 
                                                INNER JOIN  members m  ON m.id =cm.userid
                                                INNER JOIN  chat_settings cs ON cs.id = cm.room_id 
                                                WHERE       cm.setting_id = ?    
                                                AND         votedown - voteup >= 5      
                                                ORDER BY    cm.date DESC LIMIT 30 ) ddd
                                    ORDER BY   date ASC ");
$mess3->bind_param("i", $room);                              
$mess3->execute();
$mess3->store_result();
$mess3->bind_result($chatid,$chat_userid ,$message,$voteup,$votedown ,$date);

while($row = $mess3->fetch()){
  $voteup     =   $row['voteup'];
  $votedown   =   $row['votedown'];

  addToDiv1($row);

  if( $voteup - $votedown >= 5 ) {
    addToDiv2($row);
  }

  if( $votedown - $voteup >= 5 ) {
    addToDiv3($row);
  } 
}

I will just give an answer based specifically on cleaning up your code. 我将仅根据清理您的代码给出答案。 Technically you will still make the 3 calls in this scenario, but it will be cleaner because you include one function only, you don't see the script behind it. 从技术上讲,在这种情况下您仍然会进行3次调用,但由于只包含一个函数,因此看不到它后面的脚本,因此它会更干净。

As I mentioned, I am not an SQL aficionado so I can not give a good solution there (maybe you can use GROUP BY and perhaps an OR clause...I don't really know...). 正如我提到的那样,我不是SQL迷,所以不能在那里提供良好的解决方案(也许您可以使用GROUP BY OR子句...我不太了解...)。 If I were to do this, I would do a function that can return all the options: 如果要这样做,我将执行一个可以返回所有选项的函数:

/core/functions/getChatMessages.php /core/functions/getChatMessages.php

function getChatMessages($settings,$mysqli)
    {
        $id   = (!empty($settings['id']))? $settings['id'] : false;
        $type = (!empty($settings['type']))? $settings['type'] : false;
        $max  = (!empty($settings['max']))? $settings['max'] : 30;
        $mod  = '';
        // No id, just stop
        if(!is_numeric($id))
            return false;
        // equation one
        if($type == 'up')
            $mod = ' AND voteup - votedown >= 5';
        // equation two
        elseif($type == 'down')
            $mod = ' AND votedown - voteup >= 5';

        $mess = $mysqli->prepare("SELECT * from ( SELECT cm.id ,cm.userid,cm.message,cm.voteup,cm.votedown,cm.date
                            FROM chat_messages cm 
                            INNER JOIN members m  ON m.id =cm.userid
                            INNER JOIN chat_settings cs ON cs.id = cm.room_id 
                            WHERE cm.setting_id = ? {$mod}     
                            ORDER BY cm.date DESC LIMIT {$max} ) ddd
                            ORDER BY date ASC");
        $mess->bind_param("i", $id);
        $mess->execute();
        $mess->store_result();
        $mess->bind_result($chatid, $chat_userid, $message, $voteup, $votedown, $date);
        while($mess->fetch()){
            $result[] = array(
                            'chatid'=>$chatid,
                            'chat_userid'=>$chat_userid,
                            'message'=>$message,
                            'voteup'=>$voteup,
                            'votedown'=>$votedown
                        );
        }
        // Send back the data
        return (!empty($result))? $result : array();
    }

To use: 使用方法:

// Include our handy function
require_once('/core/functions/getChatMessages.php');
// Store our id for use
$settings['id'] = 100;
// Should get 30 from first select
$voteGen = getChatMessages($settings,$mysqli);
// Should get 30 from second select
$settings['type'] = 'up';
$voteUp = getChatMessages($settings,$mysqli);
// Should get 15 from third select
// Just for the heck of it, I added in a limit settings
$settings['max'] = 15;
$settings['type'] = 'down';
$voteDown = getChatMessages($settings,$mysqli);

Now that you have these stored, just use a foreach loop to place them into your view. 现在您已经存储了这些内容,只需使用foreach循环将它们放入视图中即可。 The good side of this is that you can call this where ever and when ever since the function only returns data. 这样做的好处是您可以随时随地调用此函数,因为该函数仅返回数据。 It allows you to work with the data in a view or non-view situation. 它允许您在视图或非视图情况下使用数据。 Side note, I use PDO, so if there is something ineffective with the way the mysqli is fetching, that will be why. 旁注,我使用PDO,因此如果mysqli的获取方式无效,这就是原因。 It's probably just best to fetch an assoc array to return... 最好是获取一个assoc数组以返回...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM