mysql合并特定的行

时间:2017-01-02 20:29:54

标签: mysql merge rows

当前表:

╔════════════════════════════════════════╗
║ id  ║ price ║ tax ║ sku  ║ description ║
╠════════════════════════════════════════╣
║ 123 ║ 10    ║ 1   ║ sku1 ║ Dress       ║
║ 123 ║ 0     ║ 0   ║ sku1 ║ Dress-Small ║
╚════════════════════════════════════════╝

我想要的结果:

╔════════════════════════════════════════════╗
║ id  ║ price  ║ tax ║ sku  ║ description    ║
╠════════════════════════════════════════════╣
║ 123 ║ 10     ║ 1   ║ sku1 ║ Dress-Small    ║
╚════════════════════════════════════════════╝

我想从第1行获取 id 价格 tax sku ,然后获取第二行的 description 。如何实现这一目标?

2 个答案:

答案 0 :(得分:0)

怎么样

    SELECT MAX(id) id,
           MAX(price) price,
           MAX(tax) tax,
           sku1,
           MAX(description) description
      FROM Table
     GROUP BY sku1

您没有解释如何知道第二行包含正确的描述,所以这是猜测。

答案 1 :(得分:0)

这是你的答案。示例SQL Fiddle

SELECT A.id, A.price, A.tax, A.sku, B.Description
FROM (
  SELECT *
  FROM MyTable
  WHERE description = 'Dress'
) AS A
LEFT JOIN (
  SELECT *
  FROM MyTable 
  WHERE description = 'Dress-Small'
) AS B
ON A.ID = B.ID

我会考虑仔细研究id列为您的表做什么。不妨将它删除。