在select上为唯一内容列生成唯一索引

时间:2015-01-20 23:48:39

标签: mysql

我想在select语句上生成一个附加列,该列将为唯一内容生成唯一的序列号。例如,对于下面的表格,我可能希望将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;

使用IDEALLY,输出如下..

~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中执行此操作,而不是将其构建到表中,因为查询将是ad-hoc,并且将在select时进行决策,该内容将唯一编号。< / p>

我试着搜索这个,但也许我错过了正确的术语,我在这上面写了一个空白。

1 个答案:

答案 0 :(得分: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);
相关问题