【问题标题】:MySQL views cannot have subquery in from, and don't maintain order. How can I create a view from this query?MySQL 视图中不能有子查询,并且不维护顺序。如何从此查询创建视图?
【发布时间】:2011-06-28 21:32:23
【问题描述】:

我实际上是在尝试获取每个员工当前职位的结果集。我想从中创建一个视图以供以后使用,但我发现我被难住了,并且可能缺少一个简单的解决方案。这是有问题的查询,提前致谢!

select * from 
(SELECT
appointment.employee_id,
title.`name` as title_name
FROM
appointment
INNER JOIN appointment_title ON appointment.id = appointment_title.appointment_id
INNER JOIN title ON appointment_title.title_id = title.id
order by appointment_title.effective_date DESC) tmp group by employee_id

【问题讨论】:

    标签: mysql view subquery


    【解决方案1】:

    更新:

    SELECT
        appointment.employee_id ,
        ( SELECT title.`name`
          FROM appointment_title
            INNER JOIN title
              ON appointment_title.title_id = title.id
          WHERE appointment.id = appointment_title.appointment_id
          ORDER BY appointment_title.effective_date DESC
          LIMIT 1
        ) AS title_name
    FROM appointment
    GROUP BY appointment.employee_id
    

    【讨论】:

      【解决方案2】:

      另一种选择是将查询分成两个视图。第一个视图将包含派生表子查询,第二个视图将简单地从中选择:

      CREATE VIEW vwEmployee_Inner AS
      SELECT
      appointment.employee_id,
      title.`name` as title_name
      FROM
      appointment
      INNER JOIN appointment_title ON appointment.id = appointment_title.appointment_id
      INNER JOIN title ON appointment_title.title_id = title.id
      order by appointment_title.effective_date DESC
      

      然后你原来的观点变成:

      CREATE VIEW vwEmployee AS
      SELECT * FROM vwEmployee_Inner GROUP BY employee_id
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-23
        • 1970-01-01
        • 2014-09-14
        • 1970-01-01
        • 2010-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多