我有2個表:產品和評論,其中每個產品都有很多評論:獲取獨特/獨特的成果爲SQL查詢的JOIN
表產品具有以下幾列:ID,名稱 表評論有以下幾列:id,productid,created_on,評分,評論。 productid是外鍵,而created_on是類型datetime。
的樣本數據如下:
<table>
<tr>
<th>product id</th>
<th>product name</th>
</tr>
<tr>
<td>1</td>
<td>Foo</td>
</tr>
<tr>
<td>2</td>
<td>Bar</td>
</tr>
</table>
<table>
<tr>
<th>review id</th>
<th>product id</th>
<th>rating</th>
<th>review</th>
<th>created_on</th>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>5</td>
<td>Perfect foo</td>
<td>2017-1-1Z00:00:00</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>1</td>
<td>This foo is not the foo I was looking for</td>
<td>2017-2-2Z00:00:00</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
<td>4</td>
<td>Foo-tastic</td>
<td>2017-3-3Z00:00:00</td>
</tr>
<tr>
<td>4</td>
<td>2</td>
<td>4</td>
<td>Bar is Bar/10</td>
<td>2017-3-3Z00:00:00</td>
</tr>
<tr>
<td>4</td>
<td>2</td>
<td>5</td>
<td>Barmendous!!!</td>
<td>2017-1-1Z00:00:00</td>
</tr>
</table>
我希望能夠得到最新的審查每個產品,但我不確定如何做到這一點。它應該是這樣的:
SELECT products.product_name, reviews.rating, reviews.review FROM products LEFT JOIN products ON products.id = reviews.productid ORDER BY reviews.created_on DESC;
但是,這將返回每個產品的多個結果。我只需要對每個產品進行一次評估,最好是最近的評論。
在這種情況下,MySQL 5.x或更高版本是首選數據庫。
樣品進行如下:
<table>
<tr>
<th>product name</th>
<th>rating</th>
<th>review</th>
</tr>
<tr>
<td>Foo</td>
<td>4</td>
<td>Footastic</td>
</tr>
<tr>
<td>Bar</td>
<td>4</td>
<td>Bar is Bar/10</td>
</tr>
<table>
你如何決定哪一個是最新的?有沒有表示相同的日期欄? –
請包括樣本數據和您的預期輸出。沒有表格結構,我不認爲可以給出確切的答案。 –