简体   繁体   中英

Sql query not returning proper results

im attempting to create a query that counts the occurrence of rows containing a certain steamid64 of the player from multiple tables. As of now, the query isn't returning the proper count. It seems that if the 'propsCount' is 2 and the 'killsCount' is 1 then the killsCount will be 2 for some reason. It seems like its matching the highest value in the row.

Here is the query:

SELECT users.steamid64, COUNT(props.steamid64) AS propsCount, COUNT(kills.steamid64) AS killsCount, COUNT(deaths.steamid64) AS deathsCount
FROM `sl_players` AS users
            LEFT JOIN `sl_deathLogs` AS deaths ON users.steamid64 = deaths.steamid64
            LEFT JOIN `sl_killLogs` AS kills ON users.steamid64 = kills.steamid64
            LEFT JOIN `sl_propLogs` AS props ON users.steamid64 = props.steamid64
        GROUP BY users.steamid64

Here is the returned data:

SQL数据

In the picture you can see the propsCount and the killsCount of the second player are both 2. The propsCount should be 1 and the killsCount is the proper value. Any ideas why the propsCount column is matching the killsCount column? This seems to occur when the column has at least a value of 1 and when another column has a greater value, it will match the greater value.

You should be aggregating before the JOIN . But if your matches for a given steamid64 are not too big and the tables have a unique id, then you can use the COUNT(DISTINCT) work-around:

SELECT p.steamid64,
       COUNT(DISTINCT pl.id) AS propsCount,
       COUNT(DISTINCT kl.id) AS killsCount,
       COUNT(DISTINCT dl.id) AS deathsCount
FROM sl_players p LEFT JOIN
     sl_deathLogs dl
     ON p.steamid64 = dl.steamid64 LEFT JOIN
     sl_killLogs kl
     ON p.steamid64 = kl.steamid64 LEFT JOIN
     sl_propLogs pl
     ON p.steamid64 = pl.steamid64
GROUP BY p.steamid64;

I don't know what the id is really called in the tables.

A more general solution is to aggregate before doing the JOIN or to use subqueries:

select p.steamid64,
       (select count(*) from sl_propLogs pl where p.steamid64 = pl.steamid64) as propsCount,
       (select count(*) from sl_killLogs kl where p.steamid64 = kl.steamid64) as killsCount,
       (select count(*) from sl_deathLogs dl where p.steamid64 = dl.steamid64) as deathsCount
from sl_players p;

This avoids the aggregation in the outer query. So, with appropriate indexes (on steamid64 in each of the log tables), it should be faster than the JOIN method.

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