【问题标题】:Mysql query two table join with reference tableMysql查询两表join与引用表
【发布时间】:2012-08-05 07:24:45
【问题描述】:

嗨,我有两张这样的桌子:

表 1:

name | distro1 | distro2 | distro3
----------------------------------
foo  | 001     | 002     | 003

表 2:

id  | distro 
---------------
001 | slackware
002 | redhat
003 | debian

我想得到这样的选择结果=

name | dis1      | dis2   | dis3
----------------------------------
foo  | slackware | redhat | debian

创建这些源表所需的查询。

CREATE TABLE IF NOT EXISTS `table1` (
  `name` varchar(30) NOT NULL,
  `distro1` varchar(30) NOT NULL,
  `distro2` varchar(30) NOT NULL,
  `distro3` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `table1` (`name`, `distro1`, `distro2`, `distro3`) VALUES
('foo', '001', '002', '003');

CREATE TABLE IF NOT EXISTS `table2` (
  `id` varchar(30) NOT NULL,
  `distro` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `table2` (`id`, `distro`) VALUES
('001', 'slackware'),
('002', 'readhat'),
('003', 'debian');

【问题讨论】:

  • 见规范化。如果有第四个发行版会发生什么

标签: mysql sql join correlated-subquery


【解决方案1】:

你可以有这样的东西:

通过使用INNeR JOIN,假设所有发行版都有值并且在table 2上有对应的匹配

SELECT  a.Name, 
        b.distro Distro1, 
        c.distro Distro2, 
        d.distro Distro3
FROM    myTableA a
            INNER JOIN myTableB b
                on a.distro1 = b.id
            INNER JOIN myTableB c
                on a.distro2 = c.id
            INNER JOIN myTableB d
                on a.distro3 = d.id

更新 1

SELECT  a.Name, 
        b.distro Distro1, 
        c.distro Distro2, 
        d.distro Distro3
FROM    myTableA a
            LEFT JOIN myTableB b
                on a.distro1 = b.id
            LEFT JOIN myTableB c
                on a.distro2 = c.id
            LEFT JOIN myTableB d
                on a.distro3 = d.id

【讨论】:

  • 您可能想要 LEFT JOIN。尚不清楚每一行是否每个发行版都有匹配的行。
  • 我假设每个发行版都有与另一个表对应的匹配项。但我仍然会编辑我的答案。
猜你喜欢
  • 1970-01-01
  • 2021-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-10
  • 2015-05-22
相关资源
最近更新 更多