可以将一个表中的字段值用作MySQL查询中的列名吗?

时间:2012-03-13 02:09:27

标签: php mysql database database-design

说我有两张桌子:

mysql> show columns from profiles;
+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| id           | int(11)      | NO   | PRI | NULL    | auto_increment | 
| full_name    | varchar(100) | NO   |     | NULL    |                | 
| date_of_birth| date         | NO   |     | NULL    |                | 
+--------------+--------------+------+-----+---------+----------------+
mysql> select * from profiles;
+-------------------+----------------+
| id  | full_name   | date_of_birth  |
+-----+-------------+----------------+
| 1   | John Smith  | 2000-01-01     |
| 2   | Anna Smith  | 1995-01-03     |
+-----+-------------+----------------+

mysql> show columns from language_en;
+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| column_name  | varchar(100) | NO   |     | NULL    |                | 
| label        | varchar(100) | NO   |     | NULL    |                | 
+--------------+--------------+------+-----+---------+----------------+
mysql> select * from language_en;
+-------------------+----------------+
| column_name      | label           |
+------------------+-----------------+
| id               | ID              |
| full_name        | Name            |
| date_of_birth    | DOB             |
+------------------+-----------------+

我想运行一个返回的查询:

+-------------------+----------------+
| ID  | Name        | DOB            |
+-----+-------------+----------------+
| 1   | John Smith  | 2000-01-01     |
| 2   | Anna Smith  | 1995-01-03     |
+-----+-------------+----------------+

这只是查询“SELECT * FROM profiles”,但使用标签而不是列名。如何使用列名称而不是直接输入它们? 我知道我能做到:

SELECT id AS ID, full_name AS Name, date_of_birth AS DOB FROM profiles

然而,我喜欢动态的东西:

SELECT id AS language_en.label FROM profiles, language_en WHERE language_en.column_name = profiles.COLUMN_HEADER????

非常感谢任何帮助

1 个答案:

答案 0 :(得分:1)

简短回答:我不这么认为。我认为MySQL的AS语句不接受除简单文本标签之外的任何内容。

我认为将您的国际化纳入数据库架构级别可能是错误的想法;看起来你可以通过在Web应用程序(php)层保持翻译级别来保持你的生活更加健全。毕竟,您的用户永远不需要直接查看列的名称,对吧?