php MySQL 返回静态字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6156726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:30:50  来源:igfitidea点击:

MySQL return static strings

phpmysqlstatic

提问by RANGER

I have a CMS that requires a SQL query to return options/values for a dropdown... typically it returns the rows from the table in the SQL query and fills in the dropdown options. Sometimes I just want to have two static options in the dropdown and do not want to create a whole table to manage those two unchanging items.

我有一个 CMS,它需要一个 SQL 查询来返回下拉列表的选项/值......通常它会从 SQL 查询中的表中返回行并填写下拉选项。有时我只想在下拉列表中有两个静态选项,而不想创建一个完整的表格来管理这两个不变的项目。

My questions is: Is there a MySQL query that will not query a table but will just return some static results as if it were querying a table?

我的问题是:是否有一个 MySQL 查询不会查询表,但只会返回一些静态结果,就像查询表一样?

Ideally I would like something similar to this (but static):

理想情况下,我想要类似的东西(但静态的):

SELECT value FROM `fake_table` 

And return the following:

并返回以下内容:

value
//////////////
Option One
Option Two
Option Three
Etc...

Thanks in advance for any help!

在此先感谢您的帮助!

回答by Fosco

select 'Option One' as Value
union
select 'Option Two' as Value

回答by Dan J

Assuming the syntax to select a constant value is the same in MySQL as MSSQL:

假设在 MySQL 中选择常量值的语法与 MSSQL 相同:

SELECT 'fake_value_1' AS value, 1 AS sort
UNION ALL
SELECT 'fake_value_2', 2
UNION ALL
SELECT value, 3 FROM table
ORDER BY sort, value

The sortcolumn ensures the fake values always appear at the beginning of the result set, but that the actual values are sorted by their value.

sort列确保假值始终出现在结果集的开头,但实际值按其值排序。

Notethat UNION ALL (as opposed to UNION) will not attempt to eliminate duplicates when it combines resultsets. This is legitimate assuming your static values won't duplicate any values in the actual table - this is worth keeping in mind, as UNION ALL has slightly better performance (unlikely to make a difference in this case, but a good general rule).

请注意,UNION ALL(与 UNION 相反)在组合结果集时不会尝试消除重复项。假设您的静态值不会复制实际表中的任何值,这是合理的 - 这一点值得牢记,因为 UNION ALL 的性能稍好(在这种情况下不太可能产生影响,但这是一个很好的一般规则)。

Also Note:As @Marc B mentions in the comments, it may be better separation of concerns to put the static values in your presentation layer, instead of putting that logic in the database.

另请注意:正如@Marc B 在评论中提到的,将静态值放在您的表示层中,而不是将该逻辑放在数据库中,可能会更好地分离关注点。

回答by John

Returning a stringand two columnsas a single column:

将一个字符串两列作为单列返回:

SELECT CONCAT('example string', column1, column2) AS combined FROM table;