我有三个 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 在这三个表的所有列表中都很常见。 我希望不要嵌套太多,因为实际上可能超过三个表。
最佳答案
试试这个:
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供查询。
关于MySQL如何查找几张表中的共同数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47966830/