如何对视图中的新列使用相关子查询?
我正在尝试编写一个包含 3 列的视图:行星、月亮和最大。
该视图旨在显示行星、它们的卫星以及“是”或“否”列,指示它是否是该行星最大的卫星。
仅使用一个 Basetable,我引用的列是 MoonPlanetOrbit(只有当 bodyType = 'Moon' 时才不为 null)、bodyName(月亮的名称)和largest('yes' 或 'no')。
到目前为止,这是我的尝试:
CREATE VIEW Moons (Planet, Moon, Largest)
select moonPlanetOrbited, bodyName, ('Yes' if bodyName = (SELECT top 1 moonMeanRadius from Body where moonPlanetOrbited = bodyName order by moonMeanRadius) as Largest)
如果需要,我可以提供更多信息。
谢谢, 科迪
I am trying to write a view that has 3 columns: Planet, Moon, and Largest.
The view is meant to show planets, their moons, and a Yes or No column indicating whether or not it is the largest moon for the planet.
Only one Basetable is used, and the columns I am referencing are moonPlanetOrbit (only not null if bodyType is = to 'Moon'), bodyName (name of the moon), and largest ('yes' or 'no').
Here is my attempt so far:
CREATE VIEW Moons (Planet, Moon, Largest)
select moonPlanetOrbited, bodyName, ('Yes' if bodyName = (SELECT top 1 moonMeanRadius from Body where moonPlanetOrbited = bodyName order by moonMeanRadius) as Largest)
I can provide any more information if needed.
Thanks,
Cody
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
SQL 最适合处理数据集。我的建议是使用 SELECT 语句和 MAX() 函数获取最大卫星集,然后将结果集与整个表连接起来。然后测试月亮是否等于最大的,以便打印“是”或“否”。
这是一个使用 MySQL 的示例。我创建了一个包含 MoonPlanetOrbited、bodyName、moonMeanRadius 列的 Moons 表。以下 SQL 为给定的 MoonPlanetOrbited 选择最大的 MoonMeanRadius:
现在我们有了 maxMoonRadius 的列表,将结果集与整个表连接起来并测试 MoonMeanRadius 是否等于 maxMoonRadius:
IF 语法来自 MySQL 5.5:
http://dev.mysql.com/ doc/refman/5.5/en/control-flow-functions.html#function_if
使用以下 SQL 进行测试:
SQL works best with sets of data. My advice is to get the set of largest moons using a SELECT statement and the MAX() function, and then join the result set with the whole table. Then test whether the moon is equal to the largest in order to print 'yes' or 'no'.
Here's an example using MySQL. I created a table Moons containing the columns moonPlanetOrbited, bodyName, moonMeanRadius. The following SQL selects the largest moonMeanRadius for a given moonPlanetOrbited:
Now that we have a list of maxMoonRadius, join the result set with the entire table and test if the moonMeanRadius is equal to the maxMoonRadius:
The IF syntax is from MySQL 5.5:
http://dev.mysql.com/doc/refman/5.5/en/control-flow-functions.html#function_if
Tested using the following SQL :
这是我的 MS-SQL 语法:
如果表使用 ID 作为主键,则比较 ID 而不是名称可能会更好。
Here is my MS-SQL Syntax stab at it:
If the table uses IDs as a primary key it may be better to compare the IDs instead of the names.
这是一个尽可能类似于您的方法的尝试(未经测试),因为您的想法并不遥远:
您只需要一个表前缀来实际执行与根表的关联,并确保您是在 CASE 语句中进行同类比较。
Here is an attempt (untested) that resembles your approach as closely as possible, since your idea wasn't that far off:
You just needed a table prefix to actually do the correlating to the root table, and also to make sure that you were comparing apples to apples in your CASE statement.