简体   繁体   English

MySQL:带有in子句整数的左外连接

[英]MySQL : Left Outer join with in clause integers

Table-A:表-A:
Each record in this table maintains the list of attached documents for a given user此表中的每条记录都维护给定用户的附加文档列表此表中的每条记录都维护着附加的文档

Table-B:表-B:
Each record in this table represents single attached document for a given user.此表中的每条记录代表给定用户的单个附加文档。表 2

I am trying to get list of all Table-B records for a given user along with Table-A records.我正在尝试获取给定用户的所有 Table-B 记录列表以及 Table-A 记录。 Where Table-A supportingDocIds varchar column maintains the list of Table-B's PrimaryKey idAttachedDocs(INT) using a comma separated which needs to be matched.其中 Table-A supportDocIds varchar 列使用逗号分隔来维护 Table-B 的 PrimaryKey idAttachedDocs(INT) 列表,该列表需要匹配。 So that I want/can read the corresponding Table-A columns for the matching records.这样我想要/可以读取匹配记录的相应 Table-A 列。

I tried below with no luck.我在下面尝试了没有运气。

select a.*,w.month from attacheddocs a left join weeklyhrssummary w on a.idattacheddocs in (REPLACE(w.supportingDocIds, '\'', '')) where a.userId=w.userid and a.userId=138 ;

Any solutions will be appreciated.任何解决方案将不胜感激。 Thanks.谢谢。

/Gopi /戈皮
www.AlliBilli.com www.AlliBilli.com

a.userId = w.userid in the WHERE clause makes this an implicit inner join. WHERE 子句中的a.userId = w.userid使其成为隐式内部连接。 a.idattacheddocs IN (REPLACE(w.supportingDocIds, '\'', '')) is equivalent to a.idattacheddocs = (REPLACE(w.supportingDocIds, '\'', '') because the IN operator doesn't work like you're thinking it does.. It thinks '1,2,3' is a single item, not a set of items. a.idattacheddocs IN (REPLACE(w.supportingDocIds, '\'', ''))等价于a.idattacheddocs = (REPLACE(w.supportingDocIds, '\'', '')因为 IN 运算符不起作用就像你想的那样......它认为'1,2,3'是一个项目,而不是一组项目。

You probably want:你可能想要:

SELECT a.*,
    w.month
FROM attacheddocs a
LEFT JOIN weeklyhrssummary w
    ON  a.userId = w.userid
    AND FIND_IN_SET(a.idattacheddocs,REPLACE(w.supportingDocIds, '\'', '')) <> 0
WHERE a.userID = 138;

Although you may actually want an INNER JOIN .尽管您实际上可能想要一个INNER JOIN

Be warned that storing multiple items in a single field in a relational database violates first normal form .请注意,在关系数据库的单个字段中存储多个项目违反了第一范式 That is to say, it's considered a basic design flaw.也就是说,它被认为是一个基本的设计缺陷。 There are times when most levels of normalization can be ignored for good reasons, but first normal form is virtually always incorrect to ignore.有时可以出于充分的理由忽略大多数规范化级别,但忽略第一范式实际上总是不正确的。 You should have a table with one record for each supportingDocID.您应该有一个表,其中每个supportingDocID 都有一条记录。 MySQL is unique in that it has a function like FIND_IN_SET() . MySQL 的独特之处在于它具有类似FIND_IN_SET()的功能。 Most RDBMSs don't.大多数 RDBMS 没有。

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

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