根据查询结果更新表

时间:2014-03-29 22:10:10

标签: php mysql join left-join

我有2张桌子

table 1                        and    table 2 
user_id     subtotal                  user_id    section1_id         section2_id          
1              10                       1            1                   0
2              5                        2            1                   1
1              4                        3            1                   1
3              6                        4            1                   2
3              6                        5            1                   2
4              0                        6            1                   3
5              0                        7            1                   3
6              0                        8            2                   2
7              0
8              0

我做了下一个查询,根据table1.subtotal的总和对table2.user_id进行排序,其中table2_section1id = 1

    SELECT table2.user_id, table2.section1_id, table2.section2_id, SUM( table1.subtotal ) AS total_price
    FROM table1
    LEFT JOIN table2 ON table1.user_id = table2.user_id
    AND table2.section1_id =1
    GROUP BY table2.user_id
    ORDER BY total_price DESC

我得到了下一个结果

table2.user_id        table2.section1_id        table2.section2_id           total_price
    1                        1                         0                        14
    3                        1                         1                         6
    2                        1                         1                         5
    4                        1                         2                         0
    5                        1                         2                         0
    6                        1                         3                         0
    7                        1                         3                         0

现在我需要根据此查询的类型更新table2.section2_id fileds作为下一个:

table2.section2_id
0                    first field to be = 0
1                    second field to be = table2.user_id first field value
1                    third field to be = table2.user_id first field value
1                    forth field to be = table2.user_id first field value
3                    fifth field to be = table2.user_id second field value
3                    sixth field to be = table2.user_id second field value
3                    seventh field to be = table2.user_id second field value
if there are more rows lets continue 
2                    eighth field to be = table2.user_id third field value
2                    ninth field to be = table2.user_id third field value
2                    tenth field to be = table2.user_id third field value
4                    eleventh field to be = table2.user_id forth field value
4                    twelfth field to be = table2.user_id forth field value
4                    thirteenth field to be = table2.user_id forth field value

因此直到完成所有行

请咨询

0 个答案:

没有答案