我想执行一个选择导致一组排列,而不是组合。换句话说,我想执行一个查询,该查询返回表中项目的各种数量和排列的行。同一行内不得有任何 ID 水平重复。
例如我们可以有:
9 pick 3
9 pick 5
9 pick 7
我有一个有效的查询,但我正在寻找优化它。该WHERE...AND...
子句过滤掉具有重复 ID 的行。虽然这可行,但它需要AND
为每个添加的选择(列)添加几个附加子句。需要9 pick 6
十五个!=
断言!随着拾取物品数量的增加,这可能会变得笨拙。它看起来也很臃肿。我正在寻找简单而优雅的东西。
这是我的桌子:
CREATE TABLE IF NOT EXISTS `table1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`col1` varchar(24) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=30 ;
INSERT INTO `table1` (`id`, `col1`) VALUES
(1, 'Wool Hat'),
(2, 'Wool Gloves'),
(3, 'Fleece Sweater'),
(4, 'Jean Pants'),
(5, 'Cotton T-Shirt'),
(6, 'Wool Socks'),
(7, 'Wool Blanket'),
(8, 'Cotton Boxers'),
(9, 'Fleece Pants');
这是我的查询:
SELECT * FROM
`table1` t1,
`table1` t2,
`table1` t3,
`table1` t4,
`table1` t5,
`table1` t6
WHERE
t1.id != t2.id
AND
t1.id != t3.id
AND
t1.id != t4.id
AND
t1.id != t5.id
AND
t1.id != t6.id
AND
t2.id != t3.id
AND
t2.id != t4.id
AND
t2.id != t5.id
AND
t2.id != t6.id
AND
t3.id != t4.id
AND
t3.id != t5.id
AND
t3.id != t6.id
AND
t4.id != t5.id
AND
t4.id != t6.id
AND
t5.id != t6.id
ORDER BY t1.col1, t2.col1, t3.col1, t4.col1, t5.col1, t6.col1
感谢您的任何见解!
编辑:
这个例子真的很无礼。我只是想以一种简单有效的方式完成排列的数学概念。
根据要求,这是预期结果的一半9 pick 2
。另一半是交换对。
Wool Hat + Wool Gloves
Wool Hat + Fleece Sweater
Wool Hat + Jean Pants
Wool Hat + Cotton T-Shirt
Wool Hat + Wool Socks
Wool Hat + Wool Blanket
Wool Hat + Cotton Boxers
Wool Hat + Fleece Pants
Wool Gloves + Fleece Sweater
Wool Gloves + Jean Pants
Wool Gloves + Cotton T-Shirt
Wool Gloves + Wool Socks
Wool Gloves + Wool Blanket
Wool Gloves + Cotton Boxers
Wool Gloves + Fleece Pants
Fleece Sweater + Jean Pants
Fleece Sweater + Cotton T-Shirt
Fleece Sweater + Wool Socks
Fleece Sweater + Wool Blanket
Fleece Sweater + Cotton Boxers
Fleece Sweater + Fleece Pants
Jean Pants + Cotton T-Shirt
Jean Pants + Wool Socks
Jean Pants + Wool Blanket
Jean Pants + Cotton Boxers
Jean Pants + Fleece Pants
Cotton T-Shirt + Wool Socks
Cotton T-Shirt + Wool Blanket
Cotton T-Shirt + Cotton Boxers
Cotton T-Shirt + Fleece Pants
Wool Socks + Wool Blanket
Wool Socks + Cotton Boxers
Wool Socks + Fleece Pants
Wool Blanket + Cotton Boxers
Wool Blanket + Fleece Pants
这不包括以下内容:
Wool Hat + Wool Hat
Wool Gloves + Wool Gloves
Fleece Sweater + Fleece Sweater
Jean Pants + Jean Pants
Cotton T-Shirt + Cotton T-Shirt
Wool Socks + Wool Socks
Wool Blanket + Wool Blanket
Cotton Boxers + Cotton Boxers
Fleece Pants + Fleece Pants