我有三张 table :
- mls_category
- points_martix
- mls_entry
我的第一个表(mls_category)如下所示:
*--------------------------------*
| cat_no | store_id | cat_value |
*--------------------------------*
| 10 | 101 | 1 |
| 11 | 101 | 4 |
*--------------------------------*
我的第二个表(points_martix)如下所示:
*----------------------------------------------------*
| pm_no | store_id | value_per_point | max_distance |
*----------------------------------------------------*
| 1 | 101 | 1 | 10 |
| 2 | 101 | 2 | 50 |
| 3 | 101 | 3 | 80 |
*----------------------------------------------------*
我的第三个表(mls_entry)如下所示:
*-------------------------------------------*
| user_id | category | distance | status |
*-------------------------------------------*
| 1 | 10 | 20 | approved |
| 1 | 10 | 30 | approved |
| 1 | 11 | 40 | approved |
*-------------------------------------------*
我使用以下查询来显示某些条件下的距离总和:
SELECT SUM(t1.totald/c.cat_value)
AS total_distance
FROM mls_category c
JOIN
(SELECT SUM(distance) totald, user_id, category
FROM mls_entry
WHERE user_id = 1
AND status = 'approved'
GROUP BY user_id, category) t1
ON c.cat_no = t1.category
这给了我总距离60作为total_distance,这正是我想要的。
现在,我想包含第三个表 (points_matrix) 并希望比较我的 sum(60)
是否小于或等于 80(max_distance),那么我的新值将是 60*3=180
。
所以,假设我的总和为10,那么我的新值将是10*1=10
,如果我的总和为25,那么我的新值将是10*1=10
。新值将根据点矩阵25*2=50
。
最佳答案
你可以使用MIN()
来计算你需要的value_per_point
,整个sql是这样的:
SELECT MIN(b.value_per_point) * d.total_distance FROM points_matrix b
JOIN
(
SELECT store_id, sum(t1.totald/c.cat_value) as total_distance FROM mls_category c
JOIN
(
SELECT SUM(distance) totald, user_id, category FROM mls_entry
WHERE user_id= 1 AND status = 'approved' GROUP BY user_id, category
) t1 ON c.cat_no = t1.category
) d ON b.store_id = d.store_id AND b.max_distance >= d.total_distance
关于php - 如何使用 SQL 中的 sum 函数比较列值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52849108/