SQL查询:从某个阈值中获取值

时间:2014-03-26 15:41:46

标签: mysql sql

我有这张表:

路径:

idTokenN idPath   token      isTV
   1      p1      test1      true
   2      p1      test2      false
   3      p2      test3      true
   4      p3      test4      false
   5      p3      test5      false
   6      p4      test6      false
   7      p4      test7      true
   8      p4      test8      false
   9      p4      test9      false
   10     p5      test10     true
   11     p5      test11     false
   12     p5      test12     false

关系:

    idTokenN  idTokenN2   rel
       10      11         test

我想获得包含至少一个值Istv“true”和idPath的idPath,包括通过某个阈值,即通过设置最小值和最大值。例如,如果强加为最小值:2且最多3个idPath长,我将只得到2到3之间:

    idPath  token   isTV    rel
      p1    test1   true    null
      p1    test2   false   null
      p5    test10  true    test
      p5    test11  false   null
      p5    test12  false   null

我试过这个查询,部分工作,我不知道如何设置idPath的范围:

SELECT path.idPath, path.token, path.isTV,relation.rel 
FROM path 
    LEFT OUTER JOIN relation ON(path.idTokenN=relation.idTokenN)
WHERE path.idPath IN (
        SELECT path.idPath FROM path WHERE path.isTV='true');

2 个答案:

答案 0 :(得分:1)

为什么不这一个?

SELECT path.idPath, path.token, path.isTV,relation.rel
FROM path
LEFT OUTER JOIN relation ON (path.idTokenN=relation.idTokenN)
WHERE path.idPath IN(SELECT DISTINCT path.idPath FROM path WHERE path.isTV='true')
AND path.idPath IN(SELECT DISTINCT path.idPath FROM path GROUP BY path.idPath HAVING COUNT(*) >= 2 AND COUNT(*) <= 3)

答案 1 :(得分:0)

SELECT 
    path.idPath, 
    path.token, 
    path.isTV,relation.rel 
FROM path 
LEFT OUTER JOIN relation 
    ON(path.idTokenN=relation.idTokenN)
GROUP BY idPath
HAVING SUM(isTV='true')>0
    AND COUNT(DISTINCT path.idTokenN) BETWEEN  2 AND 3