将查询表中的结果用于另一个查询

时间:2013-09-03 04:24:02

标签: mysql

有3个不同的表,从第一个表我得到“contact_id”,基于此我想将SUM写入接下来的2个表格,然后按照下面的代码中的表格减去。
我试图将第一个查询中的结果“contact_id”用于以下查询

SELECT (
    SELECT `id`
    FROM `civicrm_contact`
    WHERE `first_name` LIKE 'test2'
) AS contact_id

=============================================== ==============

SELECT (
    SELECT SUM(`total_amount`)
    FROM `civicrm_contribution`
    WHERE `contact_id`=
)
-
(
    SELECT SUM(`fee_amount`)
    FROM `civicrm_participant`
    WHERE `contact_id`= 
) As RemainingPoints

4 个答案:

答案 0 :(得分:1)

您需要使用子查询:

SELECT (
    SELECT SUM(`total_amount`)
    FROM `civicrm_contribution`
    WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' ) AS contact_id) 
)
-
(
    SELECT SUM(`fee_amount`)
    FROM `civicrm_participant`
    WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' ) AS contact_id)
) As RemainingPoints

答案 1 :(得分:0)

这可以解决您的问题:

SELECT (
    SELECT SUM(`total_amount`)
    FROM `civicrm_contribution`
    WHERE `contact_id` in (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' ) AS contact_id) 
)
-
(
    SELECT SUM(`fee_amount`)
    FROM `civicrm_participant`
    WHERE `contact_id` in (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' ) AS contact_id)
) As RemainingPoints

答案 2 :(得分:0)

您应该将子查询的结果限制为1,否则会导致错误,最好的方法是使用'='代替'like'来匹配名称

SELECT (
    SELECT SUM(`total_amount`)
    FROM `civicrm_contribution`
    WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' limit 1 ) AS contact_id) 
)
-
(
    SELECT SUM(`fee_amount`)
    FROM `civicrm_participant`
    WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' limit 1 ) AS contact_id)
) As RemainingPoints

答案 3 :(得分:0)

这可以帮到你

SELECT @s:=1+1 ,@s + 4,@s-1

o / p - @ s:= 1 + 1 | @s + 4 | @ S-1

       2  |    6|   1