0

我有一个像下面提到的那样的数据库表。

id    | lecture            | subject_id | date       | is_deleted
------|--------------------|------------|------------|-----------
 1    | Introduction       | 1          | 2012-08-10 | 0   
 2    | Structure          | 2          | 2012-08-15 | 1   
 3    | Introduction       | 2          | 2012-08-12 | 0   
 4    | Functions          | 1          | 2012-08-14 | 1   
 5    | Material           | 2          | 2012-08-18 | 0   
 6    | Requirements       | 1          | 2012-08-16 | 0   
 7    | Analysis           | 1          | 2012-08-11 | 0

我需要从这个表(讲座)中创建一个视图,它将显示一个行号。(流号)对于按日期排序的每个主题,删除 is_deleted = 1 行。简单地说,做一个流程没有。对于特定主题的每个讲座,仅按日期排序,未删除讲座。因此,由上述数据生成的视图将如下所示。

flow_no | id   | date       | lecture            | subject_id 
--------|------|------------|--------------------|------------
 1      | 1    | 2012-08-10 | Introduction       | 1          
 2      | 7    | 2012-08-11 | Analysis           | 1          
 3      | 6    | 2012-08-16 | Requirements       | 1          
 1      | 3    | 2012-08-12 | Introduction       | 2          
 2      | 5    | 2012-08-18 | Material           | 2          

我试图以多种方式做到这一点,但一切都失败了。如果有人可以帮助我解决这个问题,我们将不胜感激。(mysql)

4

2 回答 2

0
SELECT @rownum := @rownum + 1 flow_no, id, date, lecture, subject_id
FROM subjects, (SELECT @rownum := 0) r
WHERE is_deleted = 0
ORDER BY subject_id, date, id

我会把它留给你把它变成一个视图。

要重新启动每个主题的 flow_no,您有几个选择:

复制上面的查询,并将其包装为子查询,然后计算min(flow_no)分组subject_id,将其连接到上面的查询中,并从每一行中减去 min flow_no。

您可以将 subject_id 分配给一个变量,然后根据当前的 subject_id 检查该变量并每次重置 rownum 变量 - 我什至不确定这是可能的。

您可以编写一个存储过程来执行此操作 - 获取唯一 subject_id 的列表,然后为每个查询运行一堆查询并输出它们。

这些选项中没有一个对我有吸引力。如果这是我,我会放弃在查询中这样做。

于 2012-08-28T07:19:30.947 回答
0

我在另一个在线论坛成员的支持下找到了答案。以下将给出所需的确切结果。如果有任何相同的 Lecture.date 行,它会按 Lecture.id 顺序为这些行生成 flow_no。

SELECT id, lecture, Lecture.subject_id, date, c,
 (SELECT COUNT(subject_id) + 1 FROM Lecture AS l
  WHERE l.subject_id = Lecture.subject_id
  AND (l.date < Lecture.date OR (l.date = Lecture.date AND l.id < Lecture.id))
  AND is_deleted != 1
 ) AS flow_no
FROM Lecture
INNER JOIN
(
 SELECT subject_id, COUNT(subject_id) AS c
 FROM Lecture
 WHERE is_deleted != 1
 GROUP BY subject_id
) AS counts
ON Lecture.subject_id = counts.subject_id
WHERE is_deleted != 1
ORDER BY subject_id, date;
于 2012-08-29T07:03:41.577 回答