Mapping multiple values from the same table in mysql

后端 未结 1 1436
我寻月下人不归
我寻月下人不归 2021-01-28 14:34

Hi I have to get text value using value id from another table Table 1 contains value ids and table 2 contains name and value ids

Table 1 =

|SEVERITY | OCCU         


        
相关标签:
1条回答
  • 2021-01-28 14:50

    I strongly agree with @Strawberry comment, you should have used table2.id as foreign key in your table1. Because join based on value might lead to multiple mappings if there are duplicate records with same value.

    That being said, if you've unique value in table2 then you can do as follow.

    SELECT 
        sev.`name` AS SEVERITY,
        occ.`name` AS OCCURENCE,
        det.`name` AS DETECTABILITY
    FROM table1 
    LEFT JOIN table2 sev ON table1.SEVERITY = sev.`value`
    LEFT JOIN table2 occ ON table1.OCCURENCE = occ.`value`
    LEFT JOIN table2 det ON table1.DETECTABILITY = det.`value`;
    

    Note: We've used LEFT JOIN to make sure if we don't have value of any of the column mentioned in table1 we should still be able to fetch records.

    If you are sure that these 3 columns will always have value than you can also use INNER JOIN.

    0 讨论(0)
提交回复
热议问题