MySQL如何在几个表中查找公共数据[重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

我有三个MySQL表:

table1
list
a
b
c
d
e

table2
list
d
c
b
f
e

table3
list
f
e
c
b
a

我想得到的是

list
b
c
e

因为b,c,e在这三个表的所有列表中都很常见。我希望没有太多的嵌套,因为它实际上可能超过三个表。

mysql mysql-5.7
2个回答
0
投票

试试这个:

CREATE TABLE IF NOT EXISTS `table1` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `list` varchar(25),
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `table2` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `list` varchar(25),
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `table3` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `list` varchar(25),
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;

INSERT INTO `table1` (`list`) VALUES ('a');
INSERT INTO `table1` (`list`) VALUES ('b');
INSERT INTO `table1` (`list`) VALUES ('c');
INSERT INTO `table1` (`list`) VALUES ('d');
INSERT INTO `table1` (`list`) VALUES ('e');



INSERT INTO `table2` (`list`) VALUES ('d');
INSERT INTO `table2` (`list`) VALUES ('c');
INSERT INTO `table2` (`list`) VALUES ('b');
INSERT INTO `table2` (`list`) VALUES ('f');
INSERT INTO `table2` (`list`) VALUES ('e');


INSERT INTO `table3` (`list`) VALUES ('f');
INSERT INTO `table3` (`list`) VALUES ('e');
INSERT INTO `table3` (`list`) VALUES ('c');
INSERT INTO `table3` (`list`) VALUES ('b');
INSERT INTO `table3` (`list`) VALUES ('a');

查询:

Select t1.list
From table1 as t1
INNER JOIN table2 as t2
ON t1.list = t2.list
INNER JOIN table3 as t3
on t2.list = t3.list

你也可以访问sqlfiddle查询。


0
投票

你可以使用inner join如下

Select t1.list
From table1 as t1
INNER JOIN table2 as t2
ON t1.list = t2.list
INNER JOIN table3 as t3
on t2.list = t3.list

了解更多关于join的信息

© www.soinside.com 2019 - 2024. All rights reserved.