简体   繁体   中英

How to use exists on SQL Query

I have a small question on this piece of code:

WITH cps AS 
(
    SELECT 
        cp.id_campaign, ean.equipment 
    FROM 
        tbl_campaign cp
    INNER JOIN 
        tbl_equip ean ON (cp.id_campaign = ean.id_campaign)
)       
SELECT 
    COUNT(cp.id_campaign)
FROM 
    cps cp 
INNER JOIN 
    tbl_camp_associates assoc ON (cp.id_campaign = assoc.id_campaign_associate)
WHERE 
    EXISTS (SELECT * FROM tbl_already_processed_campaign cal_cp
            WHERE ID_message = 15  -- campaign processed succeeded
              AND cp.id_campaign = cal_cp.id_campaign);

This query has the purpose to validate if the equipment was remunerated in another campaign not associated.

Thanks guys!

EDIT: tbl_campaign table has all the information about a campaign, like ID, equipments, dates, wtv.

tbl_equip table it has all the information about equipments, id, imei, campaign with the equipment and price.

tbl_camp_associates table with associated campaigns. It has an rowID, campaign ID, associate campaign ID. eg: the campaign 44 has 2 associated campaigns 32 and 33. This results on 2 records on this table.

EG. Campaign 44 with the equipment 1 and 2 associated campaign (32 and 33). Success! And it was processed on the table tbl_already_processed_campaign with the right message (id_message = 15)

EG2: Campaign 45 with the equipment 1 and associated campaign (30 and 31) it must return an error, because it was remunerated on campaign 44 with different associated campaigns.

EXISTS condition is used in combination with a subquery and is considered to be met if the subquery returns at least one row. In this case, if the subquery

select * from tbl_already_processed_campaign cal_cp where ID_message = 15 AND cp.id_campaign= cal_cp.id_campaign

returns at least one row, EXISTS clause will evaluate to true and the condition will be met.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM