Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting PHP Process to MySQL

Tags:

sql

php

mysql

select c.kupon, count(*) as count
            from kuponbahis c
            join bahis b 
                on b.sonuc = c.secim 
                and b.ID = c.bahis 
            group by c.kupon
            having count(case when c.bahis ='$sonuclandirilacakbahis' then 1 end) > 0

With this query I'm getting kupon IDs and counts. Then fetching them in PHP and matching with the result of

SELECT COUNT(*) FROM kuponbahis WHERE kupon='$kuponid'

(while fetching the second query, too.) If it's a match, i'm doing some work.

But now, I want to do this in SQL directly.

My PHP code is below;

$kazananKuponlariGetirSorgu = mysql_query("select c.kupon, count(*) as count
from kuponbahis c
join bahis b 
    on b.sonuc = c.secim 
    and b.ID = c.bahis 
group by c.kupon
having count(case when c.bahis ='$sonuclandirilacakbahis' then 1 end) > 0");

while ($kazananKuponlariGetirSorgux = mysql_fetch_array($kazananKuponlariGetirSorgu)){

        $kuponid = $kazananKuponlariGetirSorgux[0];
        $tutanbahisadet = $kazananKuponlariGetirSorgux[1];


        $kupondakiBahisAdeti = mysql_query("SELECT COUNT(*) FROM kuponbahis WHERE kupon='$kuponid'");
        $kupondakiBahisAdetix = mysql_fetch_array($kupondakiBahisAdeti);

        if ($kupondakiBahisAdetix[0]==$tutanbahisadet){
            //it's a match
        }

I tried many queries but they all failed. How can I merge this two sql process to only one?

match

like image 855
Ece Avatar asked Aug 31 '26 22:08

Ece


1 Answers

The obvious way is in the having clause:

select c.kupon, count(*) as count
from kuponbahis c join
     bahis b 
     on b.sonuc = c.secim and b.ID = c.bahis 
group by c.kupon
having sum(c.bahis = '$sonuclandirilacakbahis') > 0 and
       count(*) = (SELECT COUNT(*) FROM kuponbahis WHERE kupon = '$kuponid');
like image 71
Gordon Linoff Avatar answered Sep 02 '26 13:09

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!