【问题标题】:How to get a single field in a VIEW to use in WHERE如何在 VIEW 中获取单个字段以在 WHERE 中使用
【发布时间】:2015-01-08 23:44:04
【问题描述】:

你好亲爱的堆栈溢出朋友,

我想使用位于另一个视图中的单个字段作为 WHERE 子句的参数(在另一个视图中)。但是,我找不到完成这项工作的正确方法。

我已经使用了 FIRST() 函数,但这会产生语法错误。

这可能与它选择整个第一行的事实有关,但我只想获得这一行中的一个字段。 (其实整个view只有一个字段)

/*this first view contains the value to use for the second view, called average */
CREATE OR REPLACE VIEW getAverage AS
SELECT AVG(todoitem.completiondate-todoitem.creationdate) as average from todolist
inner join todoitem on todoitem.id=todolist.id;

/*this view has a WHERE clause that should use a value in the getAverage VIEW */
CREATE OR REPLACE VIEW aboveAverage AS
SELECT * FROM todolist
inner join todoitem on todoitem.id=todolist.id
WHERE (todoitem.completiondate-todoitem.creationdate > FIRST(getAverage.average));

如果有人可以帮助我,我将非常感激。

【问题讨论】:

    标签: mysql view field where


    【解决方案1】:

    这是你想要的吗?

    CREATE OR REPLACE VIEW aboveAverage AS
        SELECT *
        FROM todolist inner join
             todoitem
             on todoitem.id=todolist.id
        WHERE (todoitem.completiondate-todoitem.creationdate > (SELECT average FROM getAverage);
    

    MySQL 确实允许在 whereselect 子句中使用子查询。您不需要第二个视图。

    【讨论】:

    • 谢谢,这就是我想要的。虽然不知何故我现在得到一个错误,即视图包含一个双“id”列。您是否知道这是怎么可能的,因为我认为我合并了这两列?如果我只选择“名称”而不是 *,效果会很好。
    • @Gaargod 。 . .明确列出所有列而不是使用* 是一种很好的做法。一种快速而简单的方法是使用using 而不是on
    猜你喜欢
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多