简体   繁体   中英

MySQL Query, calculating available funds

I'm attempting to retrieve an id of an ad, if the user has enough funds in his/her account to finance the cost of displaying the ad. I'm getting very lost though,

Mysql Schema:

campaign_deposit:
c_id (campaign id), btc (amount deposited)...

ad_view:
a_id (ad id), btc (cost of impression)...

ad:
id (ad id), uv (cost of impression)...

The MySQL error:

Unknown column 'ad.c_id' in 'where clause'

-Query:

SELECT id FROM 
( 
SELECT *, 
(
    SELECT SUM(btc) as btc FROM 
    ( 
        SELECT `btc` FROM ad_view WHERE a_id IN 
        (
            SELECT id FROM ad WHERE c_id = ad.c_id
        ) OR ad_space_id IN 
        (
            SELECT id FROM ad WHERE c_id = ad.c_id
        ) 
        UNION ALL SELECT (`btc` * -1) AS `deposit` FROM 
        campaign_deposit WHERE c_id=ad.c_id GROUP BY c_id 
    ) AS Total
) AS deposit FROM ad
) AS ad 
WHERE uv >= 0 AND click >= 0 AND uv < deposit AND click < deposit AND deleted=0 AND c_id IN 
(
    SELECT id FROM campaign WHERE publisher = 0 AND deleted=0
) LIMIT 1

We need to see your database schema in order to understand whether these queries are sensible or not. What columns are on the ad table?

If you're getting lost when writing MySQL queries, to me that's a sign that you need to break your queries down into simpler ones.

First of all, get familiar with mysql's JOIN syntax; it lets you do many of the things you're doing with nested queries, but structures them in a way that's easier to read and easier to think through.

Secondly and more importantly, I don't think you should be putting complex MySQL queries into production code if you're not absolutely confident in what they do and how they'll work. You're working in PHP, so it should be easy to run one query at a time, gather the results in variables, and use those variables in subsequent queries. That way you're not left troubleshooting one huge monolithic query; instead you can troubleshoot SELECT id FROM ad WHERE c_id = ad.c_id in isolation, which will be much easier to find a fix for (or get answers for here on SO).

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