Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

sql - Multiple Reason Tables used as a definition for 1 Table with one reason Column

I have a requirement I have 1 table which has a container with a qty and a Reason_ID.

Problem is that there are 5 different Reason tables that can define the reason but the container table has only one column. So the container table looks like the follow:

Container Name Qty ReasonID ContainerID
A222 50 LR111 AAA
A888 75 LR222 BBB
B333 32 BR111 CCC
B555 44 SR111 DDD
C777 77 BR333 EEE
question from:https://stackoverflow.com/questions/66065085/multiple-reason-tables-used-as-a-definition-for-1-table-with-one-reason-column

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You that three reference tables in one column. You can use multiple left joins:

select c.*,
       coalesce(lr.definition, br.definition, sr.definition) as reason
from containers c left join
     loss_reasons lr
     on c.reasonid = lr.reasonid left join
     bonus_reasons br
     on c.reasonid = br.reasonid left join
     scrap_reasons sr
     on c.reasonid = sr.reasonid;

I would recommend that you rethink the data model. Put all the reasons into a single table with a "category" for the reason.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...