从单个单元格中选择DISTINCT多个值

时间:2017-05-12 08:00:33

标签: php mysql sql

我们说我有下表,名为test

enter image description here

执行查询SELECT DISTINCT category FROM test ORDER BY category;将输出:

enter image description here

更改值时如下:

enter image description here

...再次调用查询SELECT DISTINCT category FROM test ORDER BY category;,我会得到:

enter image description here

但我希望得到以下内容:

enter image description here

有没有办法在SQL中执行此操作?或者我应该直接在我的PHP中执行此操作?

2 个答案:

答案 0 :(得分:0)

这里你应该有3张桌子。一个将保留类别,另一个将保留项目,最后一个将保持类别和项目之间的关系(它也称为associative table):

categories: id name
items: id name
categories_items: category_id item_id

在这种情况下,您的查询将变为:

SELECT id, name 
FROM categories 
ORDER BY name;

如果您想从类别中获取所有项目,请执行以下操作:

SELECT id, name 
FROM items 
JOIN categories_items 
  ON items.id = categories_items.item_id
 AND categories_items.category_id = 4;

答案 1 :(得分:0)

您应该定义规范化表格,但如果您仍坚持使用此表格结构,则可以尝试此查询:

WITH CatChar(aChar, remain) AS (
   SELECT LEFT(category,1), RIGHT(category, LEN(category)-1) 
      FROM test WHERE LEN(category)>0
   UNION ALL
   SELECT LEFT(remain,1), RIGHT(remain, LEN(remain)-1) FROM CatChar
      WHERE LEN(remain)>0
)
SELECT DISTINCT aChar FROM CatChar

(假设您的所有类别名称只是一个字符长度,否则您应该根据您的分隔符重新组合LEFT(...)部分进行拆分)