Search code examples
phpmysqlentity-attribute-value

mysql IF EXISTS


I have this table

UMS

id_attribute    value   order
1                MB      1
1                Gb      2
1                TB      3
...

and this table

ATTRIBUTE_VALUE
id    id_attribute          value  name     ums
 1         1                 50     hdd     GB
 2         1                 100    hdd     TB
 3         2                 15.00  price   NULL

and i want to select from ATTRIBUTE_VALUE where id_attribute=1 and if exist (UMS.value=ATTRIBUTE_VALUE.ums) then order by UMS.order end if group by ATTRIBUTE_VALUE.value

example for output :

50 GB
100 Tb

   and must to appear 
    15.00   !!! here is the problem because in my UMS table i don't have UMS for price

    but it doesn't appear

Solution

  • Update after you clarified your question - Try something like this:

    SELECT T1.*
    FROM ATTRIBUTE_VALUE T1
    LEFT JOIN UMS T2
    ON T1.id_attribute = T2.id_attribute AND T1.ums = T2.value
    ORDER BY T2.order, T1.value
    

    But note that this will fail if T1.value is greater than 1000. It might be better to convert all units to the same type before ordering them.

    Result of query:

    id  id_attribute  value  name    ums
    3   2             15.00  price     
    1   1             50     hdd     GB
    2   1             100    hdd     TB