简体   繁体   中英

Get Records From Table 1, Comparing With Multiple Records From Table 2

I have 2 tables (users and usages)

USERS TABLE

username usage

a        32

b        5

c        5

USAGES TABLE

username usage_added
a        7
b        7
c        7
a        30

I want to get all items from USERS table, that have USAGE BIGGER than X (in this case, let's say X is 30) AND if either NO RECORDS are found with the same username in USAGES TABLE or if the usage_added for this username in USAGES TABLE are SMALLER than X (30 in our case)

So in this case, it should return no records. I have a codeigniter query

$this->db->select('users.username');
$this->db->from('users');
$this->db->join('usages', 'usages.username = users.username','left');
$this->db->where("(usages.email is NULL OR (usages.usage_added<30 AND usages.username=users.username))", NULL, FALSE);
$this->db->where("users.usage>30", NULL, FALSE);

By using above query, I still get "username a" returned. Normally it should not return user A, because user a already has date 30 added. But it seems it compares to first record (a=7) and it says a<30 and it shows it again.

I hope it makes sense and somebody can help.

Written SQL Server syntax, this query should work for you:

DECLARE @usage_limit int = 30;

SELECT  A.username
FROM    users as A
        LEFT OUTER JOIN 
        (
            SELECT  username, 
                    usage_added = sum(usage_added)
            FROM    usages 
            GROUP BY 
                    username
        ) as B
            ON A.username = B.username
WHERE   A.usage > @usage_limit
    AND (B.username is null OR B.usage_added < @usage_limit)

This returns no records. Hope this helps!

You seem to be describing logic like this:

select u.*
from users u
where u.usage > 30 or
      not exists (select 1
                  from usages us
                  where us.username = u.username and
                        us.usage > 30
                 );

You should replace the 30 with a parameter if it varies.

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