MySQL如何在几个表中找到共同的数据

MySQL how to find common data in a few tables

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

您可以使用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

试试这个:

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查询