如何将表名连接到mysql中的列

时间:2017-04-14 16:43:40

标签: mysql

假设我正在加入mysql中的两个表

Owners - id, name
Pets - id, name, owner_id
SELECT pets.*, owners.* FROM pets JOIN owners ON owners.id=pets.owner_id

结果带有多个id和name列。是否有办法以区分pets.idowners.id等表格的方式返回列,而不指定每个列名称?

2 个答案:

答案 0 :(得分:0)

只需命名列?

SELECT pets.id AS pets_id,
   owners.id AS owners_id,
   pets.name AS pets_name,
   owners.name AS owners_name
FROM pets JOIN owners
ON owners.id=pets.owner_id

答案 1 :(得分:0)

表:

CREATE TABLE `my_table_name` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

查询:

SELECT GROUP_CONCAT(CONCAT(" ", table_name,".", column_name, " as `", table_name, ".", column_name, "`")) FROM information_schema.columns WHERE table_name='my_table_name';

结果:

 my_table_name.id as `my_table_name.id`, my_table_name.name as `my_table_name.name`