问题
I have a table called 'ratings' which contains an index which is a unique ascending number, ProductId which is a product code, rate1 to rate5 are the number of times each product has recieved a 1 or 5 star rating by a customer aveRate is the average rating for each product and lastSubDate should be the timestamp of when the last review for each product was submitted but it's currently empty.
id ProductId rate1 rate2 rate3 rate4 rate5 aveRate lastSubDate
18 9996637 0 0 0 0 1 5 0000-00-00 00:00:00
26 9996628 1 0 0 0 0 1 0000-00-00 00:00:00
34 9996618 0 0 0 1 0 4 0000-00-00 00:00:00
36 9996614 5 0 0 0 0 1 0000-00-00 00:00:00
48 9996592 5 0 1 0 3 3 0000-00-00 00:00:00
66 9996566 0 0 0 1 3 5 0000-00-00 00:00:00
In another table I have called 'last_rate_date' I have ProductId and the date the product was last rated under lastSubDate. In this table the Product Id's can appear several times as per the example as each row represents a time a review was submitted by a customer.
ProductId lastSubDate
9996665 2009-05-22 19:45:05
9996665 2009-08-06 11:30:07
9996665 2010-11-10 08:30:17
9996665 2011-06-10 09:15:47
9996665 2011-06-12 05:15:39
My questions is how can I modify the first table 'ratings' using SQL to insert the last time a product was reviewed under the 'lastSubDate' using the second table 'last_rate_date' to lookup the productId and the date bearing in mind each ProductId may appear mutiple times in this seconds table with differen't dates.
This needs to be one as a one off table modification to the first table. Adter this is done I will amend the script which adds data to ratings table to always add a timestamp in the future when it's updated.
回答1:
You can get most recent dates for each "ProductId" using the query below:
Select ProductId, MAX(lastSubDate)
From last_rate_date
Group By ProductId
This will produce each ProductId that appears in the second table, along with the latest date (using the MAX function). The Group By clause is needed to define what the aggregation is run against.
To further solve your problem, you can insert this Select statement into an Update statement like so:
UPDATE ratings a
INNER JOIN (
Select ProductId, MAX(lastSubDate) as finalLastSubDate
From last_rate_date
Group By ProductId ) b
ON a.ProductId = b.ProductId
SET a.lastSubDate = b.finalLastSubDate
回答2:
You can use the timestamp with CURRENT_TIMESTAMP default or you can add the date on the insert.
$date = date ("m-Y-d, H: i: s")
来源:https://stackoverflow.com/questions/16739599/insert-into-mysql-table-last-submission-date-for-a-review