I know I’ve done this before, but haven’t done much SQL in a while.
I have a table called lead_detail, it has the following columns: id, lead_id, form_id, field_number, value.
I’m trying to get results and then filter them.
So, originally, I got all the lead ids that had a particular answer for a particular question.
Let’s say the first filter was that I wanted all results for an answer of “yes” to a question of “do you like chicken” (field_number of 4).
$leadIds = query(SELECT lead_id FROM lead_detail WHERE field_number = '4' AND value = 'yes' AND form_id = '1')
$leadIds = implode(', ', $leadIds);
Then, I could get the appropriate filtered data by
SELECT * FROM lead_detail WHERE form_id = '1' and lead_id IN ($leadIds)
This works perfectly.
If I want to add a SECOND filter though, I need to do two queries to the same columns in the same query. I’m thinking I need to do some kind of join with table aliases, or some sub selects, but can’t remember how to do it.
So if I needed to know who answered “yes” to a question of “do you like chicken” AND who answered “18-24” on “what is your age”, how would I get the appropriate $leadIds?
It’d be something like the combination of
SELECT lead_id FROM lead_detail WHERE field_number = '4' AND value = 'yes' AND form_id = '1'
AND
SELECT lead_id FROM lead_detail WHERE field_number = '5' AND value = '18-24' AND form_id = '1'
An inner join would work for this:
There is possibly a neater solution however.