MySQL:使用另一个表中的值作为列别名?

时间:2013-11-26 19:24:34

标签: mysql sql alias

我们有一张非常时髦的桌子,我正在尝试从中获取描述性结果。
此表存储紧密相关但不同的数据类型集合,有意义的列“名称”存储在单独的表中。我认为展示比解释更容易。

简化和抽象示例:

 CREATE TABLE IF NOT EXISTS `something_obscure` (
      `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
      `obscure_type_id` tinyint(2) NOT NULL,
      `segment1` varchar(92) DEFAULT NULL,
      `segment2` varchar(92) DEFAULT NULL,
      `segment3` varchar(92) DEFAULT NULL,
      `datetime_created` datetime DEFAULT NULL,
      PRIMARY KEY (`id`)
    );
    INSERT INTO `something_obscure` 
      (`id`, `obscure_type_id`, `segment1`, `segment2`, `segment3`, `datetime_created`) 
    VALUES
      ('250', 1, '123', '456', '789', '2013-05-14 10:13:44'),
      ('251', 2, 'abc', 'def', 'ghk', NULL),
      ('252', 2, NULL, NULL, 'mnop', NULL);


 CREATE TABLE IF NOT EXISTS `obscure_type` (
      `id` tinyint(2) unsigned NOT NULL AUTO_INCREMENT,
      `type` varchar(30) NOT NULL,
      `description` varchar(92) DEFAULT NULL,
      `segment1` varchar(92) DEFAULT NULL COMMENT 'a LABEL/NAME for the data found in Segment1 of the Obscure table',
      `segment2` varchar(92) DEFAULT NULL,
      `segment3` varchar(92) DEFAULT NULL,
      `datetime_created` datetime DEFAULT NULL,
      PRIMARY KEY (`id`)
    );
    INSERT INTO `obscure_type` 
      (`id`, `type`, `description`, `segment1`, `segment2`, `segment3`) 
    VALUES
      (1, 'native', 'a descriptive description', 'best', 'worst', 'other'),
      (2, 'alien', 'another descriptive desc', 'in', 'out', 'stationary');


最初,我希望在业务逻辑(在php中)的列中添加有意义的名称,但是如果我能在程序之前得到SQL来处理它,甚至看到这个结果集,那么' d awesome

目标:
只是为了说明(我知道这实际上不会起作用),我想的有点像:

SELECT 
  data.segment1 AS type.segment1,
  data.segment2 AS type.segment2,
  data.segment3 AS type.segment3
FROM something_obscure AS data
JOIN pobscure_type AS type
ON data.obscure_type_id = type.id
WHERE data.obscure_type_id = 2

那会回来:

----------------------------
| in   | out  | stationary |
----------------------------
| abc  | def  | ghk        |
| NULL | NULL | mnop       |
----------------------------

概要
如何将别名设置为另一个表的 ? 我们不想指定别名,我们希望别名由引用字段的值设置。这可能吗?

2 个答案:

答案 0 :(得分:1)

您是否尝试将别名包含在backqoutes中?

SELECT 
  data.segment1 AS `type.segment1`,
  data.segment2 AS `type.segment2`,
  data.segment3 AS `type.segment3`
FROM something_obscure AS data
JOIN obscure_type AS type
ON data.obscure_type_id = type.id

答案 1 :(得分:0)

在别名周围使用单引号

SELECT 
  data.segment1 AS 'segment1',
  data.segment2 AS'segment2',
  data.segment3 AS 'segment3'
FROM something_obscure AS data
JOIN obscure_type AS type
ON data.obscure_type_id = type.id

Working fiddle demo

Other demo with type.*