我已经检查了其他堆栈溢出问题,但没有解释如何执行以下操作:
我有一个控制预订队列的应用程序,我需要列出每一行:
positionTotal
- 表示基于ID较低的所有活动(状态)行的位置。
positionSamePeople
- 表示基于所有具有较低ID和相同人数的活动(状态)行的排名。
预订表:
+---------------------------------------+
+ id INT AI +
+ status TINYINT (0-Inactive/1-Active) +
+ people INT +
+---------------------------------------+
查询:
SELECT * FROM reservation
+----------------------+
+ id | status | people +
+----------------------+
+ 1 | 1 | 3 +
+ 2 | 0 | 1 +
+ 4 | 1 | 3 +
+ 6 | 1 | 1 +
+ 8 | 1 | 2 +
+ 9 | 0 | 3 +
+ 10 | 1 | 3 +
+ 11 | 1 | 2 +
+----------------------+
我想要的是什么:
+------------------------------------------------------------+
+ id | status | people | positionTotal | positionSamePeople +
+------------------------------------------------------------+
+ 1 | 1 | 3 | 1 | 1 +
+ 4 | 1 | 3 | 2 | 2 +
+ 6 | 1 | 1 | 3 | 1 +
+ 8 | 1 | 2 | 4 | 1 +
+ 10 | 1 | 3 | 5 | 3 +
+ 11 | 1 | 2 | 6 | 2 +
+------------------------------------------------------------+
我可以查询SELECT * FROM reservation WHERE status=1
,然后在PHP中计算positionTotal
和positionSamePeople
,但这似乎不是一个好选择。
答案 0 :(得分:1)
子查询很容易做到:
SELECT r1.*,
(SELECT COUNT(*) +1
FROM reservation r2
WHERE r2.status = 1
AND r2.id < r1.id) AS positionTotal,
(SELECT COUNT(*) +1
FROM reservation r3
WHERE r3.status = 1
AND r3.people = r1.people
AND r3.id < r1.id) AS positionSamePeople
FROM reservation r1