Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I retrieve the column names from an empty MySQL select query result

Tags:

mysql

Is there a way to retrieve the column names of a query that returns no data? The result of this query would be empty. Is there a way how to find the column names when there's no result?

Please note that I'm aware of solutions using DESCRIBE and select column_name from information_schema.columns where table_name='person'; but I need a more flexible solution that will fit these multicolumn queries.

Please also note that I am still using the original PHP MySQL extention (so no MySQLi, and no PDO).

like image 841
Mariya Avatar asked Oct 15 '25 06:10

Mariya


1 Answers

If you wrap your query with the following SQL, it will always return the column names from your query, even if it is an empty query result:

select myQuery.*
from (select 1) as ignoreMe
left join (
select * from myTable where false -- insert your query here
) as myQuery on true

Note: When the results of the subquery are empty, a single row of null values will be returned. If there is data in the subquery it won't affect the output because it creates a cross-product with a single row...and value x 1 = value

like image 151
akenney Avatar answered Oct 17 '25 21:10

akenney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!