如何创建变量并将其传递给另一个查询?

时间:2016-01-10 16:09:12

标签: mysql sql

UPDATE uye SET bakiye=bakiye+100 WHERE ID IN 
(SELECT uye FROM kupon WHERE ID IN 
( select c.kupon from kuponbahis c 
join bahis b on b.sonuc = c.secim and b.ID = c.bahis 
group by c.kupon 

having sum(c.bahis = 24) > 0 and count(*) = (SELECT COUNT(*) FROM kuponbahis WHERE kupon = c.kupon)))

此查询有效但不是" 100"我想用内部变量来改变它,比如;

UPDATE uye SET bakiye=bakiye+VARIABLE WHERE ID IN 
(SELECT uye, VARIABLE FROM kupon WHERE ID IN 
( select c.kupon from kuponbahis c 
join bahis b on b.sonuc = c.secim and b.ID = c.bahis 
group by c.kupon 

我可以用PHP代码完成它,但我想直接将所有进程都放到SQL中。

(注意:是的,我想要的变量在kupon表中)

2 个答案:

答案 0 :(得分:1)

我怀疑你不想要变量。您需要子查询中的列。在这种情况下,请使用JOIN

UPDATE uye JOIN
       (SELECT k.*
        FROM kupon k
        WHERE k.ID IN (select c.kupon
                       from kuponbahis c join
                            bahis b
                            on b.sonuc = c.secim and b.ID = c.bahis 
                       group by c.kupon 
                       having sum(c.bahis = 24) > 0 and
                              count(*) = (SELECT COUNT(*) FROM kuponbahis WHERE kupon = c.kupon)
                   )
     ) k
     ON k.eye = uye.id
    SET bakiye=bakiye + k.VARIABLE; 

答案 1 :(得分:1)

如果您尝试使用存储过程,则可以声明并使用变量:

CREATE PROCEDURE setBakiye 
(
   bakiyeEkle INT
) 
BEGIN 
    UPDATE uye SET bakiye=bakiye+bakiyeEkle WHERE ID IN 
    (SELECT uye FROM kupon WHERE ID IN 
    ( select c.kupon from kuponbahis c 
    join bahis b on b.sonuc = c.secim and b.ID = c.bahis 
    group by c.kupon 

    having sum(c.bahis = 24) > 0 and count(*) = (SELECT COUNT(*) FROM     kuponbahis WHERE kupon = c.kupon)))
END;