将子查询结果添加到查询中

时间:2013-09-08 03:53:14

标签: mysql sql

我必须遵循子查询

    SELECT
    (
        SELECT SUM( `total_amount` )
        FROM `civicrm_contribution`
        WHERE `currency` = 'PCT'
        AND `contact_id` = ( SELECT `id`FROM `civicrm_contact`
        WHERE `first_name` = '' 
        UNION ALL
        SELECT `contact_id` FROM `civicrm_membership` 
        WHERE `source` = '')   
    )

-
(
    SELECT SUM(`fee_amount`)
    FROM `civicrm_participant`
    WHERE `fee_level`='puncte' 
    AND `contact_id` = (SELECT `id` FROM `civicrm_contact` 
    WHERE  `first_name` =''
    UNION ALL
    SELECT `contact_id` FROM `civicrm_membership` 
    WHERE `source` = '') 
)As RemainingPoints

我不知道如何将结果添加到以下查询

SELECT  `civicrm_contact`.first_name,`civicrm_membership`.start_date, `civicrm_membership`.end_date, `civicrm_membership`.source FROM `civicrm_contact`, `civicrm_membership` WHERE `civicrm_contact`.id = `civicrm_membership`.contact_id  AND `civicrm_membership`.source =''
UNION ALL    
SELECT  `civicrm_contact`.first_name,`civicrm_membership`.start_date, `civicrm_membership`.end_date, `civicrm_membership`.source FROM `civicrm_contact`, `civicrm_membership` WHERE `civicrm_contact`.id = `civicrm_membership`.contact_id  AND `civicrm_contact`.first_name ='test1'

我希望在查询结尾添加“RemainingPoints”

first_name; start_date;结束日期;资源; “RemainingPoints”

1 个答案:

答案 0 :(得分:0)

SELECT *
FROM (SELECT `civicrm_contact`.first_name,`civicrm_membership`.start_date,  `civicrm_membership`.end_date, `civicrm_membership`.source FROM `civicrm_contact`, `civicrm_membership` WHERE `civicrm_contact`.id = `civicrm_membership`.contact_id  AND `civicrm_membership`.source =''
      UNION ALL    
      SELECT  `civicrm_contact`.first_name,`civicrm_membership`.start_date, `civicrm_membership`.end_date, `civicrm_membership`.source FROM `civicrm_contact`, `civicrm_membership` WHERE `civicrm_contact`.id = `civicrm_membership`.contact_id  AND `civicrm_contact`.first_name ='test1'
     ) x
JOIN (SELECT (
        SELECT SUM( `total_amount` )
        FROM `civicrm_contribution`
        WHERE `currency` = 'PCT'
        AND `contact_id` = ( SELECT `id`FROM `civicrm_contact`
        WHERE `first_name` = '' 
        UNION ALL
        SELECT `contact_id` FROM `civicrm_membership` 
        WHERE `source` = '')   
        )
        -
        (
        SELECT SUM(`fee_amount`)
        FROM `civicrm_participant`
        WHERE `fee_level`='puncte' 
        AND `contact_id` = (SELECT `id` FROM `civicrm_contact` 
        WHERE  `first_name` =''
        UNION ALL
        SELECT `contact_id` FROM `civicrm_membership` 
        WHERE `source` = '') 
        ) As RemainingPoints) y