分组MySQL数据

Roh*_*pra 5 mysql group-by

我有这个表,我们称之为表一.

+----+---------+-----------------+
| 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)
Run Code Online (Sandbox Code Playgroud)

link_id是表中的主要标识符.它告诉我哪些网址出现在链接1,链接2等.

我想要的是: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 |
Run Code Online (Sandbox Code Playgroud)

...等等.

因此,您可以看到www.example.com出现两次,因为它与链接1和2相关联,但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');
Run Code Online (Sandbox Code Playgroud)

Dav*_*lls 1

SELECT url, GROUP_CONCAT(link_id) 
  FROM table1 
 GROUP 
    BY url;
Run Code Online (Sandbox Code Playgroud)

这将为您提供所有不同的 URL,每个 URL 都有一个链接 ID 列表