MySQL中用户定义的@variable为空

时间:2017-04-10 18:45:03

标签: php mysql mysql-workbench

我遇到了以下查询的问题。当我在mysql workbench中运行它时,用户定义的变量@cid正在被正确填充,但是当我在PHP中运行它时,变量是空的。我使用mysqli_query机制。

它的复杂查询,但正如我已经说过的 - 在mysql WB中运行正常,但在PHP中运行不正常。在PHP中,正确地返回计数,因此除了在@cid变量中存储值之外,整个查询看起来都有效。

查询:

SELECT count(*),@cid FROM users WHERE yfid IN 
(SELECT viewer_id 
FROM views WHERE campaign_id 
    IN (@cid:=(SELECT * FROM(SELECT campaign_id FROM views 
    where campaign_id>'$firstCampaignId' AND campaign_id 
    IN (SELECT id FROM campaigns WHERE owner_yfid 
    IN (SELECT id FROM uc_users WHERE email='$email')) 
group by campaign_id having count(*) > 1 
ORDER BY count(*) DESC LIMIT 1) AS tmp))) 
AND gender = 1 AND age < 35

编辑: 我发现在MySQL工作台中@cid在我第一次运行查询时也是NULL。当我第二次执行它时,它正确返回。那么分配逻辑可能存在一些问题?这是在执行查询后分配的,可以在第二次运行时访问吗?

1 个答案:

答案 0 :(得分:1)

尝试使用

select count(*), @cid:=V.campaign_id from
( select yfid from users
  where gender = 1 AND age < 35
) as U
inner join
( select viewer_id, campaign_id FROM views 
  where campaign_id > '$firstCampaignId'
) as V on U.yfid = V.viewer_id
inner join
campaigns as C on V.campaign_id = C.id
inner join
( select id from uc_users where email='$email' ) as UCU on C.owner_yfid = UCU.id
group by V.campaign_id
having count(*) > 1 
order by count(*) desc limit 1

我更喜欢在子查询中放置where子句以减少实际加入的行数,但我没有找到有关MySQL是否已经优化的任何信息。

看起来MySQL似乎优化了join语句,但没有优化in条款。