居家系統家具設計,專業團隊
嚴選板材,高品質不二選
隔音窗提供各式窗簾,高質感設計布料
款式種類任你挑選,專業窗藝設計師為您服務!

首頁  •  j2h 論壇 • 程式設計討論     • 

[php] MySQL 兩個資料表 UPDATE

房東:小蛙
發表時間:2011-08-25


Let's say for example you have a product table which stores information about products and a productPrice table which has pricing information and you want to update the prices based on when the product was created (in the examples below you want to discount all your older stuff to 80% of the current price).


In MySQL you can do this in one of two ways. The first is do do a join using commas, like so:


UPDATE product p, productPrice pp

SET pp.price = pp.price * 0.8

WHERE p.productId = pp.productId

AND p.dateCreated < '2004-01-01'


The second way is to use inner join syntax as shown below. This syntax is slightly more flexible as it means you can use left and right joins as well as inner joins, whereas the previous example is an implicit inner join.


UPDATE product p

INNER JOIN productPrice pp

ON p.productId = pp.productId

SET pp.price = pp.price * 0.8

WHERE p.dateCreated < '2004-01-01'


Another example of doing this in MySQL but using a left join to flag all the products that do not have assocated entries in the productPrice table is as follows:


UPDATE product p

LEFT JOIN productPrice pp

ON p.productId = pp.productId

SET p.deleted = 1

WHERE pp.productId IS null


This isn't necessarily a very realistic example as you would be more likely to want to straight out delete the non-matching entries or use a select query instead to display them in a list for editing but it illustrates how it can be done. The article about how to delete records with MySQL using a cross join uses these examples to delete instead of update.


Note that it's also possible in MySQL to update values in all the tables that are joined in the query. In this example we're doing the same query as in the first two examples but also updating the "dateUpdated" value in the product table.


UPDATE product p

INNER JOIN productPrice pp

ON p.productId = pp.productId

SET pp.price = pp.price * 0.8,

p.dateUpdate = CURDATE()

WHERE p.dateCreated < '2004-01-01'


 


http://www.electrictoolbox.com/article/mysql/cross-table-update/





  • 贊助網站       

    廣利不動產-板橋在地生根最實在--新板特區指名度最高、值得您信賴的好房仲
    完整房訊,房屋、店面熱門精選物件,廣利不動產 優質仲介,房屋租賃、買賣資訊透明,交易真安心!
    廣利不動產-新板特區指名度最高、值得您信賴的好房仲
    您的托付,廣利用心為您服務



  •  共 0 人回應

    姓名:
    佈告內容:
    其他選項: