MySQL如何在几个表中查找公共数据

时间:2017-12-25 08:04:47

标签: mysql mysql-5.7

我有三个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在这三个表的所有列表中都很常见。 我希望不要嵌套太多,因为它实际上可能超过三个表。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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进行查询。