Craig
Craig

Reputation: 2153

Can a field value from one table be used as a column name in a MySQL query?

Say I have two tables:

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     |
+-----+-------------+----------------+

and

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             |
+------------------+-----------------+

I want to run a query that returns:

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

Which is just the query "SELECT * FROM profiles" but using the labels instead of the column names. How do I do this using the column names and not entering them directly? I know I can do:

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

However I was after something dynamic like:

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

Any help would be much appreciated

Upvotes: 0

Views: 748

Answers (1)

Mike
Mike

Reputation: 964

Short answer: I don't think so. I don't think MySQL's AS statement accepts anything other than a simple text label.

I think putting your internationalization into the database schema level is probably the wrong idea; it seems like you can keep your life more sane by keeping that translation level in your web application (php) layer. After all, your users should never need to see directly what the name of your columns are, right?

Upvotes: 1

Related Questions