首页 > 解决方案 > How do I include table names in a MySQL query?

问题描述

This seems like it would be a simple setting, but I cannot find it. I do inner join queries on tables that have similar column names. It would be nice to include the table name in the query results, so the people receiving the data can differentiate more easily. For example:

Table1: id name timestamp

Table2: id name timestamp table1_id

Table3: id name timestamp table2_id

Then I tie it all together with a query:

select * from table1 
inner join table2 on table1.id=table2.table1_id 
inner join on table2.id=table3.table2_id;

The results have similar column header names:

id name timestamp id name timestamp table1_id id name timestamp table2_id

It's hard to tell the data apart. Of course the example query is short and silly and pointless. If I do an actual query with all the data it get more complicated. Couldn't the column header name include the table name?

table1.id table1.name table1.timestamp table2.id table2.name table2.timestamp table2.table1_id table3.id table3.name table3.timestamp table3.table2_id

标签: mysql

解决方案


Instead of writing

select * from

you can write

select table1.id as table1_id, 

and do the same for the other columns so that the results set would show you the names you give yourself for each column


推荐阅读