我在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 |
+----+------------+-----------+-------------+-------------------+
答案 0 :(得分:1)
我不知道你为什么两次插入相同的结果,这是不好的做法。
试试
SELECT
id, product_id , status, transaction from Table1
group by id ,product_id,status
答案 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;
一个问题是该表没有用于稳定排序的列,因此这是最佳猜测。