8

我创建了 3 个不同的表,它的编码是

CREATE TABLE `shirt` (
   `id` int(11) not null,
   `name` varchar(32),
   PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `shirt` (`id`, `name`) VALUES 
('1', 'vneck'),
('2', 'scoop neck');

CREATE TABLE `shirt_size` (
   `shirtId` int(11) not null,
   `sizeId` int(11) not null,
   PRIMARY KEY (`shirtId`,`sizeId`),
   KEY `sizeId` (`sizeId`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `shirt_size` (`shirtId`, `sizeId`) VALUES 
('1', '2'),
('1', '3'),
('1', '4'),
('1', '5'),
('2', '1'),
('2', '2'),
('2', '3'),
('2', '4'),
('2', '5'),
('2', '6'),
('2', '7');

CREATE TABLE `size` (
   `id` int(11) not null,
   `name` varchar(4),
   PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `size` (`id`, `name`) VALUES 
('1', 'xs'),
('2', 's'),
('3', 'm'),
('4', 'l'),
('5', '1x'),
('6', '2x'),
('7', '3x');

我用这个查询它

SELECT shirt.name, size.name 
FROM   shirt
       INNER JOIN
          shirt_size ON shirt_size.shirtId = shirt.id
        INNER JOIN
          size ON size.id = shirt_size.sizeId

但是结果表只显示了衬衫的名称,我也需要尺寸列显示在屏幕上。在我输入的 FROM 部分中,shirt, size但出现了错误。深入研究后,我看到很多人只将第一个表名放在 FROM 部分中。我不明白它应该如何代表该size.name列。我究竟做错了什么?

4

1 回答 1

11

它们具有相同的列名(尽管来自不同的表)。您需要ALIAS在其中一列(或两者)上提供一个,例如

SELECT shirt.name as ShirtName, 
       size.name as SizeName
FROM   shirt
       INNER JOIN
            shirt_size ON shirt_size.shirtId = shirt.id
       INNER JOIN
             size ON size.id = shirt_size.sizeId
于 2012-12-29T10:55:34.243 回答