2011-05-05 76 views
5

我有這張表,可以稱之爲表一。對MySQL數據進行分組

+----+---------+-----------------+ 
| id | link_id | url    | 
+----+---------+-----------------+ 
| 1 |  1 | www.example.com | 
| 2 |  1 | www.abc.com  | 
| 3 |  1 | www.test.com | 
| 4 |  1 | www.t1.com  | 
| 5 |  1 | www.newtest.com | 
| 6 |  1 | www.testing.com | 
| 7 |  1 | www.abc.com  | 
| 8 |  1 | www.example.com | 
| 9 |  1 | www.web1.com | 
| 10 |  1 | www.web2.com | 
| 11 |  2 | www.dear.com | 
| 12 |  2 | www.google.com | 
| 13 |  2 | www.flowers.com | 
| 14 |  2 | www.yahoo.com | 
| 15 |  2 | www.abc.com  | 
| 16 |  2 | www.dell.com | 
| 17 |  2 | www.web.com  | 
| 18 |  2 | www.example.com | 
| 19 |  2 | www.test.com | 
| 20 |  2 | www.abc.com  | 
+----+---------+-----------------+ 
20 rows in set (0.00 sec) 

link_id是排序表中的主標識符。它告訴我哪些URL出現在鏈接1,鏈接2等

我想acomplish是: 1.獲取所有的唯一URL, 2顯示該鏈接的URL屬於

所以示例輸出將是:

+-----------------+---------+ 
| url    | link_id | 
+-----------------+---------+ 
| www.example.com |  1 | 
| www.example.com |  2 | 
| www.abc.com  |  1 | 
| www.abc.com  |  2 | 
| www.test.com |  1 | 
| www.test.com |  2 | 
| www.t1.com  |  1 | 
| www.newtest.com |  1 | 
| www.testing.com |  1 | 
| www.web1.com |  1 | 

...等等。

所以你可以看到,因爲它是用兩個鏈接1和2相關www.example.com出現了兩次,但web1.com只出現一次,因爲它只屬於鏈接1.

我嘗試了好幾種不同的group by但我最終只能撓撓我的腦袋。

任何幫助表示讚賞。下面是錶轉儲如果有人需要:

CREATE TABLE IF NOT EXISTS `table1` (
    `id` int(11) unsigned NOT NULL AUTO_INCREMENT, 
    `link_id` tinyint(3) unsigned DEFAULT NULL, 
    `url` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=21 ; 

INSERT INTO `table1` (`id`, `link_id`, `url`) VALUES 
(1, 1, 'www.example.com'), 
(2, 1, 'www.abc.com'), 
(3, 1, 'www.test.com'), 
(4, 1, 'www.t1.com'), 
(5, 1, 'www.newtest.com'), 
(6, 1, 'www.testing.com'), 
(7, 1, 'www.abc.com'), 
(8, 1, 'www.example.com'), 
(9, 1, 'www.web1.com'), 
(10, 1, 'www.web2.com'), 
(11, 2, 'www.dear.com'), 
(12, 2, 'www.google.com'), 
(13, 2, 'www.flowers.com'), 
(14, 2, 'www.yahoo.com'), 
(15, 2, 'www.abc.com'), 
(16, 2, 'www.dell.com'), 
(17, 2, 'www.web.com'), 
(18, 2, 'www.example.com'), 
(19, 2, 'www.test.com'), 
(20, 2, 'www.abc.com'); 
+0

爲漂亮的桌子+1。 – GSerg 2011-05-05 16:44:39

回答

1
SELECT url, GROUP_CONCAT(link_id) 
    FROM table1 
GROUP 
    BY url; 

這會給你所有不同的網址,每個網址都有一個鏈接ID列表

1
Select url, link_id 
From Table1 
Group By url, link_id 
3

請問不是一個獨特的名單的工作?訂單是否重要?

SELECT DISTINCT url, link_id 
FROM `table1` 
ORDER BY 1, 2 
1
select * from table group by link_id,url 
1

那麼恕我直言,你應該按雙方link_id和URL,並且可能比通過URL進行排序,以便使用相同的網址在一起。

SELECT url, link_id FROM table1 
    ORDER BY url 
    GROUP BY url, link_id 
2

除非我誤解的問題,這聽起來像所有你需要的是一個DISTINCT子句:

select distinct url, link_id from table1; 
1

除非我失去了一些東西:

SELECT DISTINCT url, link_id FROM table1; 
相關問題