简体   繁体   English

如何在另一个查询中将SQL查询结果用作列?

[英]How can I use a SQL query result as a column in another query?

I got a view that returns weekday. 我的观点可以在工作日返回。 The result will be a column in WHERE clause, something like this: 结果将是WHERE子句中的一列,如下所示:

 SELECT * FROM dvtv_delivery WHERE (SELECT day FROM dvtv_weekday) = 'Y'

For example: 例如:

Today is sunday, in dvtv_weekday returns SUN In dvtv_delivery exist the column SUN 今天是星期天,在dvtv_weekday返回SUN在dvtv_delivery中存在列SUN

Is it possible in Mysql? Mysql中可能吗? When I run nothing appears 当我跑步时,什么也没出现

Using I use down below, works 使用下面我用下,工作

  SELECT * FROM dvtv_delivery WHERE SUN = 'Y'

Any answer would really be helpful! 任何答案都将真正有帮助! Sorry my bad English 对不起我的英语不好

The result will be a column in WHERE clause 结果将是WHERE子句中的一列

If that's the case (you want to compare a column), that column should be part of the same query. 如果是这种情况(您想比较一列),则该列应属于同一查询。

SELECT
    *
FROM dvtv_delivery
WHERE
    day = 'Y'

Your query, as written will execute, assuming that the subquery returns exactly one row: 假设子查询恰好返回一行,则将按书面形式执行查询:

SELECT *
FROM dvtv_delivery
WHERE (SELECT day FROM dvtv_weekday) = 'Y'

Such a query is a scalar subquery . 这样的查询是标量子查询 It must return one column and at most one row (under most circumstances). 它必须返回一列,最多返回一行(在大多数情况下)。

Often, such subqueries are correlated to the outer query. 通常,此类子查询与外部查询相关 That means that a WHERE clause connects values in the two tables. 这意味着WHERE子句连接两个表中的值。 It is not clear what a correlation clause would look like in this case, but the structure of the query is: 目前尚不清楚相关子句在这种情况下是什么样子,但是查询的结构是:

SELECT d.*
FROM dvtv_delivery d
WHERE (SELECT wd.day
       FROM dvtv_weekday wd
       WHERE wd.? = d.?  -- maybe these would be date columns?
      ) = 'Y'

This query: 该查询:

SELECT day FROM dvtv_weekday

returns a string like 'SUN' and not the name of the column SUN . 返回类似'SUN'的字符串,而不是SUN列的名称。
So WHERE is equivalent to: 因此,WHERE等效于:

WHERE 'SUN' = 'Y'

which will always return no rows. 它将始终不返回任何行。
You need something like this: 您需要这样的东西:

SELECT * FROM dvtv_delivery 
WHERE 
  CASE (SELECT day FROM dvtv_weekday) 
    WHEN 'SUN' THEN SUN
    WHEN 'MON' THEN MON
    WHEN 'TUE' THEN TUE
    WHEN 'WED' THEN WED
    WHEN 'THU' THEN THU
    WHEN 'FRI' THEN FRI
    WHEN 'SAT' THEN SAT
  END = 'Y'

I assume that the table dvtv_delivery has all these columns: SUN, MON, .... 我假设表dvtv_delivery具有所有这些列: SUN, MON, ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM