创建一个视图以添加行号。对于由列索引过滤的特定数据集

时间:2012-08-28 07:14:29

标签: mysql database view row

我有一个类似下面提到的数据库表。

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

我需要从这个表(Lecture)中查看一个视图,它将显示一行。对于按日期排序的每个主题,(流号),删除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的)

2 个答案:

答案 0 :(得分: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的列表,然后为每个执行一系列查询并输出它们。

这些选项对我来说都没什么吸引力。如果这是我,我会放弃在查询中这样做。

答案 1 :(得分: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;