search

Home  >  Q&A  >  body text

A single SQL query that will use one SELECT result in the next subquery in the same request

I'm looking for a possibility to (re)use the results of a SQL select to get the values ​​of different sub-selects within the same query

First, I should get $ValueToUse by selecting like this:

SELECT `cb_campaignid` as ValueToUse FROM `#__team_groups` WHERE `id` = '$Value'

For the "ValueToUse" result, I would like to make the next selection in the same SQL query statement if possible.

SELECT coalesce (nullif (SUM(Amount), ''), '0') as general_amount, 
(SELECT SUM(c.cb_stand) FROM #__employees c, #__team_users u where c.user_id=u.user_id and u.group=(select id from #__team_groups where cb_campaignid='$ValueToUse')) as teamleden_tussenstand, 
(select title from #__customer_campaigns where id='$ValueToUse') as title, 
(select id from #__team_groups where cb_campaignid='$ValueToUse') as groupID, 
(select goal from #__customer_campaigns where id='$ValueToUse') as goal
 FROM #__customer_payments WHERE published = 1 and campaign_id = '$ValueToUse'

What is the best way to obtain these results?

P粉195200437P粉195200437260 days ago383

reply all(1)I'll reply

  • P粉645569197

    P粉6455691972024-04-03 17:38:56

    How about using the first result as a variable?

    SELECT @ValueToUse:=
    (SELECT `cb_campaignid` as ValueToUse FROM `#__team_groups` WHERE `id` = '$Value');
    
    SELECT coalesce (nullif (SUM(Amount), ''), '0') as general_amount, 
    (SELECT SUM(c.cb_stand) FROM #__employees c, #__team_users u where c.user_id=u.user_id and u.group=(select id from #__team_groups where cb_campaignid=@ValueToUse)) as teamleden_tussenstand, 
    (select title from #__customer_campaigns where id=@ValueToUse) as title, 
    (select id from #__team_groups where cb_campaignid=@ValueToUse) as groupID, 
    (select goal from #__customer_campaigns where id=@ValueToUse) as goal
     FROM #__customer_payments WHERE published = 1 and campaign_id = @ValueToUse;

    reply
    0
  • Cancelreply