我有一个包含多行的表,如此
category1 | category2 | category3 | code | price
fruit | awesome | green | apple1 | 10.00
fruit | awesome | green | apple1b | 14.00
fruit | awesome | red | apple1 | 15.00
pasta | good | small | pasta1 | 5.00
pasta | good | small | pasta2 | 7.00
pasta | awesome | red | pasta2 | 10.00
pizza | margherita| good | pizza1 | 20.00
我需要将category1,category2和category3的所有可能组合放在一个数据库中(每行一个组合),如:
fruit | awesome | green
fruit | awesome | red
pasta | good | small
pasta | awesome | red
pizza | margherita | good
避免重复。我试过DISTINCT,但当然它只适用于独特的发现。我该如何在php中做到这一点?
答案 0 :(得分:3)
您可以使用此查询执行此操作:
select distinct category1, category2, category3 from categories;
你可以在这个SQL小提琴中看到它是如何完成的,以及结果:http://sqlfiddle.com/#!9/a423c/1
答案 1 :(得分:0)
http://sqlfiddle.com/#!9/a7967/1
SELECT t1.category1, t2.category2, t3.category3
FROM (
SELECT DISTINCT category1
FROM table1) t1
LEFT JOIN (
SELECT DISTINCT category2
FROM table1) t2
ON 1
LEFT JOIN (
SELECT DISTINCT category3
FROM table1) t3
ON 1