Php SQL独立内部联接
我不知道这个sql,sql能做到吗 我有一张桌子 表:tree_hiePhp SQL独立内部联接,php,mysql,sql,Php,Mysql,Sql,我不知道这个sql,sql能做到吗 我有一张桌子 表:tree_hie cluster | id 1 | X | Y 2 | X | Y | Z 3 | A | B 表:价值 id | value x | 3 y | 3 z | 3 a | 0 b | 0 我想这样展示 cluster | value | id 1 | 3 | x,y 2 | 3 | x,y,z 3 | 0 |a,
cluster | id
1 | X | Y
2 | X | Y | Z
3 | A | B
表:价值
id | value
x | 3
y | 3
z | 3
a | 0
b | 0
我想这样展示
cluster | value | id
1 | 3 | x,y
2 | 3 | x,y,z
3 | 0 |a,b
请你知道如何提出这样的问题。。我不知道。。非常感谢您。如果我理解正确,您需要两个表之间的连接:
select th.cluster,
min(v.value) as value,
group_concat(v.id) as ids
from tree_hie th join
value v
on concat('|', th.id, '|') like concat('%|', v.id, '|%')
group by th.cluster;
您已将ID列表存储在单个字段中,并使用竖条作为分隔符。这是一个糟糕的数据结构。您应该使用一个连接表,每个集群一行,一个id
编辑:
如果分隔符真的是带空格的“|”
:
on concat('| ', th.id, ' |') like concat('%| ', v.id, ' |%')
您还可以使用
replace
先用逗号替换空格和
管道,然后使用find_in_set
select t.cluster,
min(v.`value`) as value,
group_concat(v.id order by v.id) as id
from tree_hie t
join `value` v on (
find_in_set(
v.id,replace(replace(t.id,'|',','),' ','')
) > 0
)
group by t.cluster
但是有这样的结构真的很糟糕,你应该首先考虑数据结构
规范化数据,否则您将陷入(编程)痛苦的世界MySQL没有任何好的机制来处理分隔列表,如
X | Y | Z
,并对其进行连接。设置字段cluster
表中的外键value
,然后使用在树上连接。cluster=value。cluster
谢谢大家,巴玛,阿什库法拉兹。。我的数据库,一定是这样的。。4.我只是在想弗雷奇。。在php中,在树上使用分隔id,但我无法将其分组。我的数据库必须是这样的。。4.我只是在想弗雷奇。。我不知道gordon,不显示任何东西,我在MySQLWorkbenchi上试试如果你的分隔符中有空格,那么你也需要考虑一下。等等。。在我的表上,值id没有分隔符,分隔符|就在树的表上。。这是对的?在concat(“|”,v.id,“|”)上,像concat(“%|”,th.id,“|%”)谢谢gordon,我用分隔符尝试了所有可能的方法,但是不能工作谢谢khalid它工作了。。但是对于在php中执行不能。。你知道怎么做吗?@tara如果你还有其他问题,你可以通过添加有关错误的所有详细信息来问一个新问题