[英]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. 我知道我以前做过这个,但是有一段时间没有做太多的SQL。
I have a table called lead_detail, it has the following columns: id
, lead_id
, form_id
, field_number
, value
. 我有一个名为lead_detail的表,它有以下列:
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. 所以,最初,我得到了所有针对特定问题的特定答案的主要ID。
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). 让我们说第一个过滤器是我希望所有结果对“你喜欢鸡”(field_number为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. 如果我想添加SECOND过滤器,我需要对同一查询中的相同列执行两次查询。 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? 因此,如果我需要知道谁对“你喜欢鸡”这个问题回答“是”并且在“你的年龄是多少”时回答“18-24”,我将如何得到合适的$ 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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.