我有两张桌子,
表1
userid filter
thiru 1
thiru 2
thiru 3
raja 1
raja 2
表2
headline filter1 filter2
test 1 3
test2 1 2
如果我想选择适用于过滤器的用户
当我选择测试时 - thiru适用(filter1和filter2)匹配
当我选择test2时 - thiru和raja适用(filter1和filter2)匹配。
基本上过滤器是有条件的。
以下是我尝试的查询:
select userid
from table1
where filter in (select filter1
from table2
where headline = 'test')
and filter in (select filter2
from table2
where headline = 'test');
请给我这个查询。 提前谢谢。
答案 0 :(得分:3)
答案 1 :(得分:2)
基本上,您希望将table1中的过滤器上的两个表连接在一起= = filter1或= filter2,并且您只希望在连接列表中出现两次的用户名。这就是小组所做的=>将表格连接在一起后,它会将用户名出现的次数分组。然后是HAVING COUNT(*)> 1排除仅出现一次的所有用户名(即仅匹配filter1或filter2中的一个)
SELECT
userid
FROM
table1 t1
INNER JOIN
table2 t2
ON
t1.filter=t2.filter1 OR
t1.filter=t2.filter2
WHERE
t2.headline = 'test'
GROUP BY
userid
HAVING COUNT(*) > 1
你自己的查询实际上几乎正常,但它有一个致命的缺陷:
你在(某事物)中编写WHERE过滤器并在(somethingelse)中过滤。数字1永远不会=同时为1和3,所以没有一行其过滤器可以同时为1和3 ..有不同的行可以匹配这个,但为此你的查询需要是:
select userid from table1
where
filter in (select filter1 from table2 where headline = 'test') OR
filter in (select filter2 from table2 where headline = 'test')
我只将AND更改为OR ..这将为THIRU返回两行,为RAJA返回一行,因此我们仍然需要对其进行分组并计算它们:
select userid from table1
where
filter in (select filter1 from table2 where headline = 'test') OR
filter in (select filter2 from table2 where headline = 'test')
GROUP BY username HAVING COUNT(*)>1
Soo ..你很亲密,你只需要逐行思考事情
答案 2 :(得分:0)
SELECT userid FROM table1 WHERE(过滤IN(SELECT filter1 FROM table2 WHERE headline ='test')或过滤IN(SELECT filter2 FROM table2 WHERE headline ='test'));
答案 3 :(得分:0)
您可以使用以下结构来获得结果
select a.userid
from table1 a
join table2 b on (a.filter = b.filter1 or a.filter = b.filter2)
where b.headline = 'test'
group by a.userid