如果在其他列中有多于1个值,则多次选择1行

时间:2013-03-01 16:39:32

标签: mysql sql select

我有一个数据库结构。问题是该表格非常复杂(错字3)。

我将简化为:

|     ID   |CAT  | 
|==========|=====|
|1         |44,15|
|2         |16   |
|3         |29,30|

我想要的结果是每个CATEGORY(CAT)有1行,这意味着

1 44
1 15
2 16
3 29
3 30

我尝试使用简单的选择,但当然它不起作用。

我还尝试使用表格CATEGORY使用CATEGORY.id IN (TABLE1.cat)

进行左连接

2 个答案:

答案 0 :(得分:0)

1。:你的数据库结构不好!它甚至不是First Normal Form(1NF),因为你在列中有一个数组作为字符串表示。

2。:这并不是那么棘手。

一些灵感:http://blog.fedecarg.com/2009/02/22/mysql-split-string-function/或此处:http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_substring-index

答案 1 :(得分:0)

如果你在cat中只有两个值:

select id, left(cat, locate(',', cat) - 1)
from t
where cat like '%,%'
union all
select id, substr(cat, locate(',', cat) + 1, length(cat))
from t
where cat like '%,%'
union all
select id, cat
from t
where cat not like '%,%'

如果您有类别列表,则可以执行以下操作:

select t.id, c.cat
from t join
     categories c
     on concat(',', c.cat, ',') like concat('%,', t.cat, ',%')