在后续行上显示空结果

时间:2014-03-12 16:27:50

标签: mysql sql

我在MySQL中有以下表格

+----+------------+-----------+-------------+-------------------+
| id | product_id |  status   | transaction |      action       |
+----+------------+-----------+-------------+-------------------+
|  1 |          2 | Pending   |             | sent              |
|  2 |          2 | Complete  |           1 | received          |
|  2 |          2 | Complete  |           1 | some other action |
+----+------------+-----------+-------------+-------------------+

我想在完成状态后只显示一次交易。 所以结果集是

+----+------------+-----------+-------------+-------------------+
| id | product_id |  status   | transaction |      action       |
+----+------------+-----------+-------------+-------------------+
|  1 |          2 | Pending   |             | sent              |
|  2 |          2 | Complete  |           1 | received          |
|  2 |          2 | Complete  |             | some other action |
+----+------------+-----------+-------------+-------------------+

2 个答案:

答案 0 :(得分:1)

我不知道你为什么两次插入相同的结果,这是不好的做法。

试试

     SELECT  
         id, product_id , status, transaction from Table1
     group by id ,product_id,status

http://sqlfiddle.com/#!2/3102b/1

答案 1 :(得分:1)

在MySQL中执行此操作的最简单方法是使用变量。查询看起来像这样:

select id, product_id, status,
       if(id <> @previd and @prevstatus <> status and status = 'Complete', transaction, NULL) as transaction,
       action,
       @previd := id, @prevstatus := status
from table t cross join
     (select @previd := -1, @prevstatus := '') const
order by id, product_id, status;

一个问题是该表没有用于稳定排序的列,因此这是最佳猜测。