2015-01-20 77 views
0

我想要在选择语句上生成一个额外的列,将生成唯一的内容序列号。例如,对于下面的表格,我可能希望将一个Ad-Hoc索引添加到所选国家/地区的输出中。生成唯一索引的唯一内容列在选择

我不希望将此索引内置到表中,目标是让任何查询都能够为唯一内容的任何列分配唯一编号。见下文。

DROP TABLE IF EXISTS `phone`; 

CREATE TABLE `phone` (
    `id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT, 
    `country` DECIMAL(5,0) UNSIGNED NOT NULL, 
    `area` DECIMAL(5,0) UNSIGNED NOT NULL, 
    `number` DECIMAL(8,0) UNSIGNED NOT NULL, 
    `extension` DECIMAL(5,0) UNSIGNED DEFAULT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8; 

INSERT INTO `phone` (`country`, `area`, `number`, `extension`) VALUES (44, 9876, 54321, 42); 
INSERT INTO `phone` (`country`, `area`, `number`, `extension`) VALUES (22, 9873, 64321, 42); 
INSERT INTO `phone` (`country`, `area`, `number`, `extension`) VALUES (22, 9874, 64321, 42); 
INSERT INTO `phone` (`country`, `area`, `number`, `extension`) VALUES (33, 9875, 64321, 42); 
INSERT INTO `phone` (`country`, `area`, `number`, `extension`) VALUES (33, 9877, 64321, 42); 
INSERT INTO `phone` (`country`, `area`, `number`, `extension`) VALUES (55, 9878, 64321, 42); 
INSERT INTO `phone` (`country`, `area`, `number`, `extension`) VALUES (55, 9879, 64321, 42); 
INSERT INTO `phone` (`country`, `area`, `number`, `extension`) VALUES (55, 9870, 64321, 42); 

select '~Magic_Happens_Here~' , country,area,number from phone 
order by country; 

与理想的情况下,如下的输出..

~Magic_Happens_Here~ country area number 
1      22  9873 64321 
1      22  9874 64321 
2      33  9875 64321 
2      33  9877 64321 
3      44  9876 54321 
4      55  9870 64321 
4      55  9878 64321 
4      55  9879 64321 

这样做的原因是为了方便后选择演示文稿。重要的是能够在select中执行此操作,而不是将其构建到表中,因为查询将是临时的,并且将在选择时作出决定,哪些内容唯一编号。

我试过寻找这个,但也许我错过了正确的术语,我在这里画了一个空白。

回答

0

好的,我正在寻找的答案是RANK函数,MySQL不直接支持,所以要做到这一点如下。

select FIND_IN_SET(country, @values_set) as rank, 
country, area,number from phone, 
(SELECT @values_set := GROUP_CONCAT(
DISTINCT country 
ORDER BY country);