mysql - sql 连接表,其中 1 列有逗号

标签 mysql sql

当我搜索“new1”时,如何获取所有用户名。例如:我应该获取 A 和 B,因为 tblC 中的用户 ID 1,2 对于具有 new1 的 row1 来说是 1,2。我应该使用什么查询来获取以上结果? 我真的很感谢任何帮助。提前致谢。
http://sqlfiddle.com/#!2/1ab8e/2

CREATE TABLE if not exists tblA
(
id int(11) NOT NULL auto_increment ,
user varchar(255),
 category int(255),
 PRIMARY KEY (id)
);

CREATE TABLE if not exists tblB
(
id int(11) NOT NULL auto_increment ,
username varchar(255),
 userid int(255),
 PRIMARY KEY (id)
);

CREATE TABLE if not exists tblC
(
id int(11) NOT NULL auto_increment ,
nname varchar(255),
 userids varchar(255),
 PRIMARY KEY (id)
);


INSERT INTO tblA (user, category ) VALUES
('1', '1'),
('1', '2'),
('1', '3'),
('1', '1'),
('2', '1'),
('2', '1'),
('2', '1'),
('2', '1'),
('3', '1'),
('2', '1'),
('4', '1'),
('4', '1'),
('2', '1');


INSERT INTO tblB (userid, username ) VALUES
('1', 'A'),
('2', 'B'),
('3', 'C'),
('4', 'D'),
('5', 'E');


INSERT INTO tblC (id, nname,userids ) VALUES
('1', 'new1','1,2'),
('2', 'new2','1,3'),
('3', 'new3','1,4'),
('4', 'new4','3,2'),
('5', 'new5','5,2');

到目前为止的查询:

select * where nname="new1" from  tblC
CROSS JOIN tblB
ON tblB.userid=(SELECT userids FROM substr(tblC.userids,','))

最佳答案

你真的应该看看Database normalization并首先通过添加连接表来标准化您的结构,并保存来自 tablec 的关系。tablec 中存储的每个关系将存储在新的连接表中,但不是以逗号分隔的列表,每行将保存 c 的 id 和每行一个用户 id,如果您无法更改您的架构,您可以使用 find_in_set查找集合中的值

select *  
from  tblC c
JOIN tblB b
ON (find_in_set(b.userid,c.userids) > 0)
where c.nname="new1"

See demo

<小时/>

编辑规范化架构

我已删除userids来自您的专栏tblC相反,我创建了一个新的联结表作为 tblC_user有 2 列 c_id这将与 tblC 的 id 列相关第二个userid存储 tblC 的用户关系用户请参阅 tblC 的示例架构

CREATE TABLE if not exists tblC
(
id int(11) NOT NULL auto_increment ,
nname varchar(255),
 PRIMARY KEY (id)
);

INSERT INTO tblC (id, nname) VALUES
('1', 'new1'),
('2', 'new2'),
('3', 'new3'),
('4', 'new4'),
('5', 'new5');

这是您的联结表 tblC_user

CREATE TABLE if not exists tblC_user
(
 c_id int,
 userid int
);

INSERT INTO tblC_user (c_id,userid) VALUES
('1','1'),
('1','2'),
('2','1'),
('2','3'),
('3','1'),
('3','4'),
('4','3'),
('4','2'),
('5','5'),
('5','2');

在上面,如果您注意到我没有存储任何逗号分隔的关系 tblC 用户的每个关系存储在新行中,对于您关心的结果集,我在连接中使用了联结表,新查询也将如下所示

select *  
from  tblC c
join tblC_user cu on(c.id = cu.c_id)
join tblB b on (b.userid = cu.userid)
where c.nname="new1"

Demo 2

现在可以通过使用索引来优化上述查询,您可以轻松维护级联关系

关于mysql - sql 连接表,其中 1 列有逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45160151/

相关文章:

sql - PostgreSQL 加入不使用特殊字符

C# SQL 数据适配器 System.Data.StrongTypingException

php - 创建表 : Syntax error

mysql - 在一对多关系表中获取最低共享值

mysql - 这个查询应该做什么? (为什么会失败?)

php - 不显示空的 img src 框或没有数据/值的空行

mysql - 如何在 MySQL 中的分组列中进行搜索? (如果可能,也在 Hibernate 中)

mysql - 多对多关系数据困惑

mysql - SQL 选择带过滤器的行

php - 选择 3 个随机字符串,然后在 PHP 中用逗号分隔它们