2015-01-20 62 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);