简体   繁体   中英

Best way to store configuration in MySQL

I have a scenario where i need to store configurations in mysql table having three columns namely VendorID , ServiceID and ModeID . Configuration for a vendor can be done with three overriding cases as follows.

  1. One column VendorID having non-NULL value with ServiceID ,ModeID having NULL value.

VendorID,ServiceID,ModeID -- > 1,NULL,NULL

  1. Two columns VendorID,ServiceID having non-NULL values with ModeID having NULL value.

VendorID,ServiceID,ModeID -- > 1,1,NULL

  1. All three columns having non NULL values.

VendorID,ServiceID,ModeID -- > 1,1,1

When case 1,2,3 are defined and in the MySQL query WHERE clause vendorid,servideid and modeid are passed, then case 3 overrides case 2 and case 1.

When case 3 is not defined and case 1,2 are defined and in the MySQL query WHERE clause vendorid,servideid and modeid are passed, then case 2 overrides case 1.

When case 3 and case 2 are not defined and case 1 is defined and in the MySQL query WHERE clause vendorid,servideid and modeid are passed, then case 1 is returned.

Now my question is, how can i query the table to get the configuration returned when vendorid,servideid and modeid are passed in the query in one go without having to query 3 times separately.

Any other good approach for the above problem is also welcome.

You may want this:

where (VendorID, ServiceID, ModelID) = ($VendorID, $ServiceID, $ModelID) or
      ( (VendorID, ServiceID) = ($VendorID, $ServiceID) and ModelId is null) or
      ( VendorID = $VendorID and ServiceID is null and ModelId is null)

Alternatively you may want:

select t.*
from t
where VendorId = $VendorId and
      (ServiceId = $ServiceId or ServiceId is null) and
      (ModelId = $ModelId or ModelId is null)
order by ( ServiceId is not null ) desc,
         ( ModelId is not null ) desc
limit 1;

This returns one row with the best match.

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.

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