Table-A:
Each record in this table maintains the list of attached documents for a given user
Table-B:
Each record in this table represents single attached document for a given user.
I am trying to get list of all Table-B records for a given user along with Table-A records. 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. So that I want/can read the corresponding Table-A columns for the matching records.
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
a.userId = w.userid
in the WHERE clause makes this an implicit inner join. 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.
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
.
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. MySQL is unique in that it has a function like FIND_IN_SET()
. Most RDBMSs don't.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.