I have a table in my database which i want to extract data in a specific order.
Here is an example of the table:
CREATE TABLE `test` (
`field1` int(11) NOT NULL,
`field2` int(11) DEFAULT NULL,
`field3` int(11) DEFAULT NULL,
UNIQUE KEY `field1_2` (`field1`,`field2`),
UNIQUE KEY `field1_3` (`field1`,`field3`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Valid entries in my table is:
- field1 must be filled
- field2 can be either null or an unique value based on field1 and field2
- field3 can be either null or an uniqie value based on field1 and field3
The order i want to extract the data is:
- all fields with field2 and field3 as null
- all fields with field2 as null and field3 with values
- all fields with field3 as null and field2 with values
So far i have used three queries connected with UNION
SELECT * FROM test WHERE field2 IS NULL
AND field3 IS NULL UNION
SELECT * FROM test WHERE field2 IS NULL
AND field3 IS NOT NULL UNION
SELECT * FROM test WHERE field2 IS NOT NULL
AND field3 IS NULL;
I myself feel this is to much necessary code to get it in order and hoped there was a better solution.
So is there a better way?