我想在以下查询中添加某种“容差”。这意味着,我可以指定一个值,该值表示四个(子)选择返回行中的多少个>所以如果这个值是2,我只想加入这两个表。有没有办法实现这一点?
SELECT distinct(user_id) FROM
(SELECT user_id FROM table1 WHERE ...) as t1
INNER JOIN
(SELECT user_id FROM table1 WHERE ...) as t2
ON t1.user_id=t2.user_id
INNER JOIN
(SELECT user_id FROM table1 WHERE ...) as t3
ON t1.user_id=t3.user_id
INNER JOIN
(SELECT user_id FROM table1 WHERE ...) as t4
ON t1.user_id=t4.user_id
修改 每个子查询的可能结果如下:
t1 t2 t3 t4
0 0 0
1 1 1 1
2 2 2 2
3 3
如果所有这些子结果都加入,则会导致:1,2。 如果我添加公差因子为1,我希望我的结果为0,1,2因为只缺少一个“0”。如果因子为2,则结果为0,1,2,3,因为缺少两个“3”和一个“0”。我希望这更清楚。
答案 0 :(得分:0)
如果我理解了您的问题,您可以在子选择中添加变量并在以下后过滤:
SELECT distinct(user_id) FROM
(SELECT user_id, 1 as table_from FROM table1 WHERE ...) as t1
INNER JOIN
(SELECT user_id, 2 as table_from FROM table1 WHERE ...) as t2
ON t1.user_id=t2.user_id
INNER JOIN
(SELECT user_id, 3 as table_from FROM table1 WHERE ...) as t3
ON t1.user_id=t3.user_id
INNER JOIN
(SELECT user_id, 4 as table_from FROM table1 WHERE ...) as t4
ON t1.user_id=t4.user_id
WHERE table_from <= 2;
答案 1 :(得分:0)
解决方案是联合所有子选择并计算它们如下:
SELECT distinct(user_id), sum(t) as tolerance FROM (
SELECT user_id, 1 as t FROM table1 WHERE ... GROUP BY...
UNION ALL
SELECT user_id, 1 as t FROM table1 WHERE ... GROUP BY...
UNION ALL
SELECT user_id, 1 as t FROM table1 WHERE ... GROUP BY...
UNION ALL
SELECT user_id, 1 as t FROM table1 WHERE ... GROUP BY...
) as x GROUP BY ... HAVING tolerance <= 2
然后你可以指定应该返回多少个子选项(这里:2)。