简体   繁体   中英

optimize query: get all votes from user's item

i did it my way because i'm very bad getting results from two tables...

Basically, first i get all the id items that correspond to the user, and then i calculate the ratings of each item.

But, there is two different types of object item, so i do this 2 times: show you:

    function votos_usuario($id){

//            $previa = "SELECT id FROM preguntas WHERE id_usuario = '$id'";
//            $r_previo = mysql_query($previa);
//            $ids_p = '0, ';
//            while($items_previos = mysql_fetch_array($r_previo)){
//                $ids_p .= $items_previos['id'].", ";
//                //echo "ids pregunta usuario: ".$items_previos['id']."<br>";
//            }
//            $ids = substr($ids_p,0,-2);
//            //echo $ids;
//
//            $consulta = "SELECT valor FROM votos_pregunta WHERE id_pregunta IN ( $ids )";
//            //echo $consulta;
//
//           $resultado = mysql_query($consulta);
//           $votos_preguntas = 0;
//           while($voto = mysql_fetch_array($resultado)){
//             $votos_preguntas = $votos_preguntas + $voto['valor'];
//           }
$votos_preguntas= 0;
$votos_preguntas = mysql_query("SELECT SUM(valor) FROM votos_pregunta WHERE id_pregunta IN (SELECT id FROM preguntas WHERE id_usuario = '$id')");



           $previa_r = "SELECT id FROM recetas WHERE id_usuario = '$id'";
            $r_previo_r = mysql_query($previa_r);
            $ids_r = '0, ';
            while($items_previos_r = mysql_fetch_array($r_previo_r)){
                $ids_r .= $items_previos_r['id'].", ";
                //echo "ids pregunta usuario: ".$items_previos['id']."<br>";
            }
            $ids = substr($ids_r,0,-2);
            $consulta_b = "SELECT valor FROM votos_receta WHERE id_receta IN ( $ids )";
            //echo $consulta;

           $resultado_b = mysql_query($consulta_b);
           $votos_recetas = 0;
           while($voto_r = mysql_fetch_array($resultado_b)){
             $votos_recetas = $votos_recetas + $voto_r['valor'];
           }





            $total = $votos_preguntas + $votos_recetas;
            return $total;

        }

As you can si this is two much.. O(n^2)

Feel like thinking?

thanks!

You can do this for both:

$votos_preguntas = mysql_query("SELECT SUM(valor) FROM votos_pregunta WHERE id_pregunta IN (SELECT id FROM preguntas WHERE id_usuario = '$id')");

If votos_pregunta and votos_rectas have the same structure, I would only have it as one table with a newly added type column that could be either rectas or preguntas. Then you need to only do one statement for $total .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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