简体   繁体   中英

Compare Two Tables, Get Value From Table and Multiply It - PHP MySQL

I'm newbie and need help about PHP MySQL.

I have two tables:

Table1:

Home | Work | Sport |Buy YES| BUY NO
_ __ _ __ _ __ _ __ _ __ _ __ _ __
Television | Laptop | shoes | |
DVD |desk |ball | |


Table2:

Items | Buy | Budget
_ __ _ __ _ __ _ __ _ __ _ __ _ __
Television | YES | 500
Television | NO | 5
Laptop | YES | 400
Laptop | NO | 3
shoes | YES | 80
shoes | NO | 1
DVD | YES | 60
DVD | NO | 2
desk | YES | 700
desk | NO | 1
ball | YES | 20
ball | NO | 1

How can I get value from "Table2" and multiply each the value and store it in the next column in "Table1" ?

for example:

Buy YES = Television * Laptop * shoes = 500*400*80

Buy NO = Television * Laptop * shoes = 5 * 3 * 1

and also do to the next row. I wish you understand what I mean.

Thanks for your help.

Your db schema is a nightmare, but you can do it this way

UPDATE table1 t LEFT JOIN table2 h_yes
    ON t.home = h_yes.items 
   AND h_yes.buy = 'YES' LEFT JOIN table2 h_no
    ON t.home = h_no.items 
   AND h_no.buy = 'NO' LEFT JOIN table2 w_yes
    ON t.work = w_yes.items 
   AND w_yes.buy = 'YES' LEFT JOIN table2 w_no
    ON t.work = w_no.items 
   AND w_no.buy = 'NO' LEFT JOIN table2 s_yes
    ON t.sport = s_yes.items 
   AND s_yes.buy = 'YES' LEFT JOIN table2 s_no
    ON t.sport = s_no.items 
   AND s_no.buy = 'NO'
   SET t.buy_yes = COALESCE(h_yes.budget, 1) 
                 * COALESCE(w_yes.budget, 1) 
                 * COALESCE(s_yes.budget, 1),
       t.buy_no = COALESCE(h_no.budget, 1) 
                 * COALESCE(w_no.budget, 1) 
                 * COALESCE(s_no.budget, 1);

Outcome:

|       HOME |   WORK | SPORT |  BUY_YES | BUY_NO |
|------------|--------|-------|----------|--------|
| Television | Laptop | shoes | 16000000 |     15 |
|        DVD |   desk |  ball |   840000 |      2 |

Here is SQLFiddle demo

It might be worth revising your tables. I'm not sure they're suitable as a row in Table 1 (to my understanding) doesn't represent a single item/instance.

Irregardless, you'll want to look at Mysqli for PHP found here: PHP Manual - Mysqli 1 .

Mysqli will allow you to retrieve data from you MySQL Database and from there, you can use PHP to do the manipulation required.

In theory, you'll want to use Mysqli to return a data set using a given SQL query. Then using PHP, iterate through each row of the data set and perform the necessary functions.

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