我无法在FROM子句中创建包含子查询的视图

时间:2013-02-14 11:19:45

标签: mysql view mysql-workbench

数据来源是:

Start Time              Real End Time           Staff
2013-02-14 16:44:27     2013-02-14 18:44:27     P 
2013-02-14 16:44:08     2013-02-14 17:09:08     C
2013-02-14 16:42:51     2013-02-14 16:43:51     P
2013-02-14 16:31:26     2013-02-14 17:06:26     V
2013-02-14 16:04:02     2013-02-14 16:34:02     C

当我使用时:

CREATE VIEW turn_times AS
SELECT staff AS name, start_time, real_end_time AS work_end_time
FROM (  SELECT staff, start_time, real_end_time
        FROM treatments 
        WHERE date(real_end_time) = curdate()
        ORDER BY real_end_time ASC) AS a
GROUP BY name

我得到了:

mysql #1349 - View's SELECT contains a subquery in the FROM clause

我想通过使用视图获取以下数据,有什么好的解决方案:

name    start_time             work_end_time
C       2013-02-14 16:04:02    2013-02-14 16:34:02
P       2013-02-14 16:42:51    2013-02-14 16:43:51
V       2013-02-14 16:31:26    2013-02-14 17:06:26

我不想为这个问题创建两个视图,我可以在一个视图中获得正确的sql吗?

2 个答案:

答案 0 :(得分:0)

您是否尝试使用聚合函数(ORDER BY)来返回每个MIN的{​​{1}}日期,而不是将子查询与min()一起使用:

staff

请参阅SQL Fiddle with Demo

然后转入视图:

SELECT staff, 
  min(start_time),
  min(real_end_time)AS work_end_time
FROM treatments 
WHERE date(real_end_time) = curdate()
group by staff

以上版本会复制您提供的结果,但如果您想要结束时间,则可能需要使用以下内容。这将为您提供每位员工的实际开始时间和结束时间:

CREATE VIEW turn_times AS
SELECT staff, 
  min(start_time),
  min(real_end_time)AS work_end_time
FROM treatments 
WHERE date(real_end_time) = curdate()
group by staff

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

目前尚不清楚您使用子查询的原因,但您可以在没有子查询的情况下实现类似的结果

CREATE VIEW turn_times AS
SELECT staff AS name, 
  MIN(start_time) AS start_time,
  MAX(real_end_time) AS work_end_time,
  date(start_time) As turn_date
FROM treatments 
WHERE 
AND date(start_time) = curdate()
AND date(real_end_time) = curdate()
GROUP BY staff, date(start_time);