I have 2 tables:
CREATE TABLE plans (id int, benefit varchar(5), clip_state int); INSERT INTO plans (id, benefit, clip_state) VALUES (1, 'A', 1), (2, 'A', 0), (3, 'B', 0), (4, 'C', 0); CREATE TABLE clip_states (state varchar(2), clip_state int); INSERT INTO clip_states (state, clip_state) VALUES ('LA', 1), ('FL', 0);
Note that clip_state is 0 or 1, and the data model allows you to query for one or not a plan in the plans table from two data: benefit and state , Firstly, using the benefit condition, we can filter the plans table for a maximum of two rows, one with clip_state = 0 and one = 1. Then, using state and joining the clip_states table clip_states we can reduce the result to one row (or zero) by checking:
- If
state is in the clip_states table, make sure clip_state matches the two tables. If there is no match, the result is not returned. - If
state does not exist in clip_states , it only matches a row in the plans table that has clip_state = 0.
Here is my query that does the trick:
SELECT id, p.clip_state, benefit FROM plans p LEFT JOIN clip_states cs ON STATE IN ('LA') WHERE benefit = 'A' AND (p.clip_state = cs.clip_state OR (p.clip_state = 0 AND cs.clip_state IS NULL));
As you can see, the left join is rather strange because it does not join the relationship between the two tables. So my question is:
- Is it normal to have such a connection?
- Is there a better solution (clean and efficient)?
You can check my solution at: http://sqlfiddle.com/#!1/8912d/53
Updated 1: I updated the text above.
Updated 2: Additional Information
- If a
state not in the clip_states table, then its clip_state implicitly 0. Otherwise, its clip_state is in the table. - From the two data:
benefit and state find the row in the plans table, where plans.clip_state = clip_state of what state indicates. Of course, if this does not match, the string is not returned.