我创建了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
列。我做错了什么?
答案 0 :(得分: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