简体   繁体   中英

SQL multiple selects on same table and column for data filtering

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:

SELECT DISTINCT(ld1.lead_id)
FROM lead_detail ld1
INNER JOIN lead_detail ld2 ON (ld1.lead_id = ld2.lead_id)
WHERE ld1.field_number = '4' AND ld1.value = 'yes' AND ld1.form_id = '1' 
AND ld2.field_number = '5' AND ld2.value = '18-24' AND ld2.form_id = '1'

There is possibly a neater solution however.

Couldn't you just use

SELECT lead_id 
FROM lead_detail 
WHERE ((field_number = '4' AND value = 'yes') OR (field_number = '5' AND value = '18-24')) AND form_id = '1'

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