Need query for JOIN four tables with some conditions?
05:08 31 Oct 2018

I have the following four tables:

1) mls_user 2) mls_category 3) bonus_point 4) mls_entry

In mls_user table values are like below:

*-------------------------*
| id | store_id | name    |
*-------------------------*
| 1  |    101   | sandeep |
| 2  |    101   | gagan   |
| 3  |    102   | santosh |
| 4  |    103   | manu    |
| 5  |    101   | jagveer |
*-------------------------*

In mls_category table values are like below:

*---------------------------------*
| cat_no |  store_id |  cat_value |
*---------------------------------*
|   20   |   101     |     1      |
|   21   |   101     |     4      |
|   30   |   102     |     1      |
|   31   |   102     |     2      |
|   40   |   103     |     1      |
|   41   |   103     |     1      |
*---------------------------------*

In bonus_point table values are like below:

*-----------------------------------*
| user_id | store_id |  bonus_point |
|   1     |   101    |     10       |
|   4     |   101    |      5       |
*-----------------------------------*

In mls_entry table values are like below:

*-------------------------------------------------------*
| user_id | store_id |  category |  distance |  status  |
*-------------------------------------------------------*
|    1    |   101    |    20     |    10     | Approved |
|    1    |   101    |    21     |    40     | Approved |
|    1    |   101    |    20     |    10     | Approved |
|    2    |   101    |    20     |     5     | Approved |
|    3    |   102    |    30     |    10     | Approved |
|    3    |   102    |    31     |    80     | Approved |
|    4    |   101    |    20     |    15     | Approved |
*-------------------------------------------------------*

And I want below output:

*--------------------------------------------------*
|  user name  | Points | bonus Point | Total Point |    
*--------------------------------------------------*
|   Sandeep   |   30   |     10      |    40       |
|   Santosh   |   30   |     0       |    30       |
|   Manu      |   15   |     5       |    20       |
|   Gagan     |   5    |     0       |     5       |
|   Jagveer   |   0    |     0       |    0        |
*--------------------------------------------------*

I tell the calculation of how the points will come for user Sandeep. Points = ((10+10)/1 + 40/4)=30 Here 1 and 4 is cat value which comes from mls_category.

I am using below code for a particular user but when i

 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 store_id='101' AND status='approved' 
           group by user_id, category) t1 on c.cat_no = t1.category

I have created tables in online for checking DEMO

sql mysql