具有以下表结构:
CREATE TABLE `shirt` (
`id` INTEGER NOT NULL,
`name` VARCHAR(32),
PRIMARY KEY( `id` )
);
CREATE TABLE `size` (
`id` INTEGER NOT NULL,
`name` VARCHAR(4),
PRIMARY KEY( `id` )
);
CREATE TABLE `shirt_size` (
`shirtId` INTEGER NOT NULL,
`sizeId` INTEGER NOT NULL,
PRIMARY KEY( `shirtId`, `sizeId` ),
FOREIGN KEY( `shirtId` ) REFERENCES `shirt`( `id` ),
FOREIGN KEY( `sizeId` ) REFERENCES `size`( `id` )
);
而这个数据:
INSERT INTO
`shirt` ( `id`, `name` )
VALUES
( 1, "vneck" ),
( 2, "scoop neck" );
INSERT INTO
`size` ( `id`, `name` )
VALUES
( 1, "xs" ), ( 2, "s" ), ( 3, "m" ),
( 4, "l" ), ( 5, "1x" ), ( 6, "2x" ), ( 7, "3x" );
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 );
在 MySQL 中,你可以这样做:
SELECT
`shirt`.`id`,
`shirt`.`name`,
GROUP_CONCAT( `size`.`name` ) as `sizes`
FROM
`shirt`
JOIN
`shirt_size`
ON `shirt_size`.`shirtId` = `shirt`.`id`
JOIN
`size`
ON `size`.`id` = `shirt_size`.`sizeId`
GROUP BY `shirt`.`id`;
这将导致类似:
+----+------------+-------------------+
| id | name | sizes |
+----+------------+-------------------+
| 1 | vneck | s,m,l,1x |
+----+------------+-------------------+
| 2 | snoop neck | xs,s,m,l,1x,2x,3x |
+----+------------+-------------------+
不确定其他RDBMS是否具有类似于 MySQL 的聚合函数GROUP_CONCAT()
。如果没有,那么使用类似的东西:
SELECT
`shirt`.`id`,
`shirt`.`name` as `shirtName`,
`size`.`name` as `sizeName`
FROM
`shirt`
JOIN
`shirt_size`
ON `shirt_size`.`shirtId` = `shirt`.`id`
JOIN
`size`
ON `size`.`id` = `shirt_size`.`sizeId`;
这将为您提供每种尺寸的多行,每件衬衫。