I am building a dynamic application which will act based on settings.
The settings are stored in a MySQL table which consists of both App level data and global level data (app_id = 0)
.
My use case is, I want to select the settings of an App. If it does not exist, fetch the corresponding setting from the global level.
I have achieved this using sub queries and COALESCE
function.
Question: Can the data be fetched in a single query? If not, Can the schema be modified to handle this App level and Global level in a much simpler way?
Schema
CREATE TABLE `settings` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`partner_id` int(11) NOT NULL,
`app_id` int(11) DEFAULT NULL,
`type` varchar(64) DEFAULT NULL,
`name` varchar(64) DEFAULT NULL,
`value` varchar(300) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `key_partner_id` (`partner_id`),
KEY `key_app_id` (`app_id`),
KEY `key_type` (`type`),
KEY `key_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Data
| id | partner_id | app_id | type | name | value |
|----|------------|--------|-------|---------|--------|
| 1 | 500 | 0 | color | primary | blue |
| 2 | 500 | 100 | color | primary | green |
| 3 | 500 | 101 | color | primary | red |
query
SELECT * FROM settings WHERE app_id in (
COALESCE ((SELECT app_id FROM settings WHERE app_id = 100), 0)
);
| id | partner_id | app_id | type | name | value |
|----|------------|--------|-------|---------|-------|
| 2 | 500 | 100 | color | primary | green |
SELECT * FROM settings WHERE app_id in (
COALESCE ((SELECT app_id FROM settings WHERE app_id = 102), 0)
);
| id | partner_id | app_id | type | name | value |
|----|------------|--------|-------|---------|-------|
| 1 | 500 | 0 | color | primary | blue |
How can I fetch data from these tables in one query?
,How can I modify the table to reduce queries?
andHow to improve the App level, Global level segregation?
. At least the first question is on-topic (IMO), not sure about the others. In the current form the question is probably too broad. So I am not sure what to do, either. – MEE Feb 15 '18 at 15:17