【问题标题】:MySQL how to find common data in a few tables [duplicate]MySQL如何在几个表中查找公共数据[重复]
【发布时间】:2017-12-25 08:04:47
【问题描述】:

我有三个 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


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多