Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

mysql - How to normalize comma separated values within column of table and then run query

Let's say I have a table with the following structure:

 | column1    |    column2       |
 |------------|------------------|
 | a          |    1,L,3,K,5,    |
 | b          |    R,6,7,8,9     |
 | c          |    8,9,10,D      |
 | d          |    1,2,3,H       |

Let's say that column1 can potentially continue on through z and that column2 can continue on with random numbers and letters. I would like a general solution that can apply to any number of rows and columns, and number of values in column2.

I want to run a query in MySQL that will search all the values in column2 and output the letters in column1 that contain a 3 in column2. The output should be:

 | column1    |
 |------------|
 | a          | 
 | d          |  

Many posts have answers with queries that directly accomplish this, but I would like to do it the correct way. I am new to sql, but I believe that would mean to normalize the data in column2 by creating a new table and running a query on this new table instead.

Can someone help me with the code to normalize and run this query in MySQL? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To normalize this table, you would want to use a table consisting of two columns, with the primary key being both columns. It would look something like this:

| column1    |    column2       |
|------------|------------------|
| a          |    1             |
| a          |    3             |
| a          |    L             |
| b          |    R             |
| c          |    8             |
| d          |    3             |

Then you can use this simple query:

Select column1 from table where column2 = 3;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...