Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select only fieldname when using show columns query in mysql

Tags:

mysql

I use this query to select fields in a given table. Is it possible to select only the fieldname and not the whole structure of the table?

SHOW COLUMNS FROM student
like image 335
Wern Ancheta Avatar asked Apr 11 '11 04:04

Wern Ancheta


2 Answers

You're trying to determine the table structure? You can query MySQL's information_schema database directly for the fieldnames:

select COLUMN_NAME from information_schema.COLUMNS where TABLE_NAME='student';
like image 153
Marc B Avatar answered Oct 14 '22 08:10

Marc B


The solution mentioned here earlier is not the correct one. Example:

CREATE DATABASE db1;
CREATE DATABASE db2;
CREATE TABLE db1.t ( id_1 INT);
CREATE TABLE db2.t ( id_2 INT);
SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME  ='t';

This will display:

+-------------+
| COLUMN_NAME |
+-------------+
| id_1        |
| id_2        |
+-------------+

suggesting that the table t has two column which is obviously not true. This query lists all the columns of the tables called t in all of your databases.

Instead, you should specify which database contains the table t you want to select the column names from:

SELECT COLUMN_NAME 
    FROM information_schema.COLUMNS 
    WHERE 
        TABLE_NAME = 't' AND 
        TABLE_SCHEMA = 'db1';
like image 30
Csongor Halmai Avatar answered Oct 14 '22 07:10

Csongor Halmai