想要加入查询中的第四张表

时间:2018-10-30 11:30:51

标签: sql mysqli

我有四个表:

  1. mls_category
  2. points_matrix
  3. mls_entry
  4. bonus_points

我的第一个表(mls_category)如下:

*--------------------------------*
| cat_no |  store_id | cat_value |
*--------------------------------*
|   10   |    101    |     1     |
|   11   |    101    |     4     |
*--------------------------------*

我的第二张表(points_matrix)如下:

*----------------------------------------------------*
| pm_no |  store_id | value_per_point | maxpoint     |
*----------------------------------------------------*
|   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 |
*-------------------------------------------*

我的第四张桌子(bonus_points)如下:

*--------------------------------------------*
| user_id |  store_id | bonus_points | type  |
*--------------------------------------------*
|    1    |    101    |      200     | fixed |
|    2    |    102    |      300     | fixed |
|    1    |    103    |       4      |  per  |
*--------------------------------------------*

现在,我想根据store_id,user_id和类型将奖励积分值添加到总距离中。

我正在使用以下代码获取总距离:

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.maxpoint >= d.total_distance

上面的代码对于计算值是正确的,现在我想加入我的第四张表。

这使我得出总和(60 * 3 = 180)。现在,我想要用户1的(60 + 200)* 3 = 780,并存储ID 101,并且值是固定的。

1 个答案:

答案 0 :(得分:1)

我认为您的查询将如下所示

SELECT Max(b.value_per_point)*( max(d.total_distance)+max(bonus_points)) FROM mls_point_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 group by store_id
) d ON b.store_id = d.store_id inner join bonus_points bp on bp.store_id=d.store_id

DEMO fiddle