2012-08-05 82 views
0

您好,我有兩個表是這樣的:Mysql的查詢的兩個表參照表連接

表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 

查詢需要crea那些源表格。

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'); 
+0

查看正常化。如果有第四個發行版會發生什麼 – Strawberry 2014-09-14 07:42:07

回答

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 
+0

您可能需要LEFT JOIN。目前還不清楚每個發行版的每個發行版是否都有匹配的行。 – 2012-08-05 07:45:46

+0

我認爲每個發行版都有與其他表格相對應的匹配。但我仍然會編輯我的答案。 – 2012-08-05 07:55:26