简体   繁体   English

在JOIN上获取SQL查询的唯一/不同结果

[英]Get Unique/Distinct results for SQL Query on JOIN

I have 2 tables: products and reviews, where each product has many reviews: 我有2个表格:产品和评论,其中每个产品都有很多评论:

table products has the following columns: id, name table reviews has the following columns: id, productid, created_on, rating, review. 表产品具有以下列:id,名称表评论具有以下列:id,productid,created_on,等级,评论。 Where the productid is a foreign key, and created_on is type datetime. 其中productid是外键,而created_on是datetime类型。

Sample data as follows: 样本数据如下:

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

I want to be able to get the latest review for each product but I'm unsure how to do it. 我希望能够获得每种产品的最新评论,但是我不确定该怎么做。 It should be something like: 应该是这样的:

SELECT products.product_name, reviews.rating, reviews.review FROM products LEFT JOIN products ON products.id = reviews.productid ORDER BY reviews.created_on DESC;

But this will return multiple results for each product. 但这将为每个产品返回多个结果。 I only need one review for each product, preferably the most recent review. 我只需要对每个产品进行一次审核,最好是最近一次审核。

MySQL 5.x or above is the preferred database in this case. 在这种情况下,首选MySQL 5.x或更高版本的数据库。

Sample out is as follows: 样本如下:

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

If you want the latest review for each product, then use a WHERE clause: 如果您想要每个产品的最新评论,请使用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
                       );

Do your query around the other way: 用另一种方式来查询:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM