Question

I am trying to get the column names from 2 tables.

I tried a query like: (SHOW COLUMNS FROM users) UNION (SHOW COLUMNS FROM posts) but that does not work & returns a syntax error. I tried the same query using DESCRIBE but that did not work either. How can I get all the column names from multiple tables in a single query? Is it possible?

Was it helpful?

Solution

From the docs for version 5.0 (http://dev.mysql.com/doc/refman/5.0/en/show-columns.html)

"SHOW COLUMNS displays information about the columns in a given table" 

So you can't really use it on multiple tables. However if you have information_schema database then you could use it like follows:

select column_name 
from `information_schema`.`columns` 
where `table_schema` = 'mydb' and `table_name` in ('users', 'posts');

Here you'd have to replace the mydb with your database name, or just use DATABASE().

OTHER TIPS

Yes use the information_Schema views.

SELECT * FROM information_schema.columns
WHERE Table_Name=? OR Table_name=?;

Use them as they are a standards way of querying database metadata.

If you also would like to get the name of the table column is from select table_name too

SELECT column_name, table_name 
FROM `information_schema`.`columns` 
WHERE `table_schema` = DATABASE() AND `table_name` in ('table1', 'table2');

I am assuming that you actually want to list all columns of the tables involved in a join.


There is a neat trick to view the qualified table and column names in a select statement. First EXPLAIN the select query, then look at the result of SHOW WARNINGS:

EXPLAIN SELECT * FROM users JOIN posts ON users.id = posts.user_id;
SHOW WARNINGS;

The result will look something like this:

Level Code Message
Note 1003 /* select#1 */ select `testdb`.`users`.`id` AS `id`,`testdb`.`users`.`name` AS `name`,`testdb`.`posts`.`id` AS `id`,`testdb`.`posts`.`user_id` AS `user_id`,`testdb`.`posts`.`name` AS `name` from `testdb`.`users` join `testdb`.`posts` where (`testdb`.`users`.`id` = `testdb`.`posts`.`user_id`)

The resulting query contains fully qualified name of all columns inside the select clause instead of *.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top