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

时间:2017-06-12 02:27:01

标签: mysql sql left-join

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

表产品包含以下列:id,name 表评论包含以下列: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>

2 个答案:

答案 0 :(得分:2)

如果您想要对每种产品进行最新审核,请使用Console.prototype.log = function log(...args) { write(this._ignoreErrors, this._stdout, `${util.format.apply(null, args)}\n`, this._stdoutErrorHandler); }; 子句:

WHERE

答案 1 :(得分: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;