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

标签 mysql sql left-join

我有 2 个表:产品和评论,其中每个产品都有很多评论:

表 products 有以下列:id, name 表 reviews 有以下列:id、productid、created_on、rating、review。其中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>

最佳答案

如果您想要每个产品的最新评论,请使用 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
                       );

关于mysql - 在 JOIN 上获取 SQL 查询的唯一/不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44490595/

相关文章:

php - 从mysql的mediumtext字段中提取一部分文本,用php制作turn.js书页

MySQL CASE 基于之前的 CASE 值

mysql - 计数时获取最后完成的(某些条件)id

sql - Azure SQL : can’t ping the Private Endpoint from on-prem

php - 基于用户级别不同的mysql join查询

mysql - 属性 'mongoOperations' 抛出 NoSuchMethodException

mysql - 我应该如何处理游戏的纸牌分配?

sql - 在没有排列的情况下找到数组的所有可能组合

sql - Postgresql 串行每日记录计数

sql - 将一个表中缺失的记录复制到新表中