【问题标题】:Why isn't this SQL code working?为什么这段 SQL 代码不起作用?
【发布时间】:2012-12-14 09:27:43
【问题描述】:

我创建了 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 列。我做错了什么?

【问题讨论】:

    标签: php mysql sql database


    【解决方案1】:

    它们具有相同的列名(虽然来自不同的表)。您需要在其中一列(或两者)上提供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
    

    【讨论】:

    • 谢谢!!!!.. 我昨晚想通了,但这是正确的答案,所以我仍然标记了它。 :)
    猜你喜欢
    • 2010-09-18
    相关资源
    最近更新 更多