简体   繁体   English

选择单个单元格中的多个值

[英]SELECT DISTINCT multiple values from a single cell

Let's say I have the following table, called test : 假设我有下表,称为test

在此处输入图片说明

Executing the query SELECT DISTINCT category FROM test ORDER BY category; SELECT DISTINCT category FROM test ORDER BY category;执行查询SELECT DISTINCT category FROM test ORDER BY category; will output: 将输出:

在此处输入图片说明

When changing a value as follows: 如下更改值时:

在此处输入图片说明

…and calling the query SELECT DISTINCT category FROM test ORDER BY category; …并调用SELECT DISTINCT category FROM test ORDER BY category;的查询SELECT DISTINCT category FROM test ORDER BY category; again, I'll get: 再次,我会得到:

在此处输入图片说明

But I want to get the following instead: 但是我想得到以下内容:

在此处输入图片说明

Is there a way to do this in SQL? 有没有办法在SQL中做到这一点? Or should I do this directly in my PHP? 还是应该直接在PHP中执行此操作?

You should have 3 tables here. 您应该在这里有3张桌子。 One will hold the the categories, the other one will hold the items and the final one will hold the relations between categories and items (it is also known as associative table ): 一个将保存类别,另一个将保存项目,最后一个将保存类别和项目之间的关系(也称为关联表 ):

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

Your query in this case will become: 在这种情况下,您的查询将变为:

SELECT id, name 
FROM categories 
ORDER BY name;

If you want to get all items from a category you could do: 如果要从某个类别中获取所有项目,则可以执行以下操作:

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

You should definetely normalize your tables but if you still insist on this table structure, you can try this query: 您应该定义表的规范化,但是如果您仍然坚持使用此表结构,则可以尝试以下查询:

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

(Assuming your all category names are just one char length, otherwise you should reorganeze LEFT(...) part to split according to your separator) (假设所有类别名称仅一个字符长,否则您应重组LEFT(...)部分以根据分隔符进行拆分)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM