2017-06-12 61 views
0

我有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>

+1

你如何決定哪一個是最新的?有沒有表示相同的日期欄? –

+0

請包括樣本數據和您的預期輸出。沒有表格結構,我不認爲可以給出確切的答案。 –

回答

2

如果你想爲每個產品的最新審覈,然後用WHERE子句:

SELECT p.product_name, r.* 
FROM products p LEFT JOIN 
    reviews r 
    ON p.id = r.productid AND 
     r.created_on = (SELECT MAX(r2.created_on) 
         FROM reviews r2 
         WHERE r2.productid = r.productid 
         ); 
+0

ahhhhh這是有道理的。非常感謝! –

1

做的其他方式查詢:

SELECT r.*, p.* 
FROM reviews AS r 
LEFT JOIN products AS p 
    ON p.id = r.productid 
GROUP BY r.productid 
ORDER BY r.date DESC; 
+0

您應該格式化您的答案,以便它們可讀。這個在房子上。 –

+0

謝謝,更新了樣本數據和預期的輸出。 –

+0

用'SELECT *'做一個'GROUP BY'就是錯的。認爲'ORDER BY'在'GROUP BY'之前是錯誤的。 –