简体   繁体   中英

Mysql SUM based another calculated filed condition

There are three tables Users, Lists, Details. Here it is my table structure and data sample

userid username   |  list_id  list_val  user_id  |   detail_id   list_id   multipler
1      user1      |     1       500        1     |      1           1         3
2      user2      |     2       300        1     |      2           1         2
3      user3      |     3       600        1     |      3           2         1
                        4       100        2            4           2         1
                                                        5           3         4

SELECT
users.username,
SUM(lists.lists_var),
FROM
users
INNER JOIN lists ON users.userid = lists.user_id
GROUP BY
users.username
HAVING
(SELECT (exp(sum(log(COALESCE(details.multipler, 1))))) FROM details WHERE
details.list_id = lists.list_id) > 3

This query gives me result

user1 - 1400

But I want something IF multipler_total > 3 THEN SUM(list_val) so result must be:

user1 - 1100

try this:

SELECT
users.username,
SUM(lists.lists_var),
FROM
users
INNER JOIN lists ON users.userid = lists.user_id
INNER JOIN (SELECT list_id, SUM(multiplier) mult_total FROM details GROUP BY list_id) d
ON d.list_id = lists.list_id and d.mult_total > 3
GROUP BY
users.username

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