根据多个条件获取结果

时间:2014-12-16 18:05:21

标签: mysql sql select conditional-statements

我的头被困在这上面了。我想要以下内容:

我想找到符合这两个标准的编号: (title =' T2' AND val> = 2)和(title =' T3' AND val> = 4)

因此在这种情况下结果为3:

| nr    | title   | val       |
|:------|--------:|:---------:|
| 1     |      T1 |    1     
| 1     |      T2 |    5
| 1     |      T3 |    3
| 3     |      T1 |    2
| 3     |      T2 |    2
| 3     |      T3 |    4

如您所见,只有nr = 3符合这两个标准。 如何编写一个返回nr = 3的查询?

这当然不起作用

SELECT DISTINCT nr FROM table WHERE title = 'T2' AND val >= 2 AND title = 'T3' AND val >= 4

不应该那么难,对吧?我曾经做过类似的事情加入桌面......

2 个答案:

答案 0 :(得分:1)

您要求的查询是:

SELECT DISTINCT nr FROM tbl WHERE title='T2' AND val >=2
AND nr IN
(
SELECT nr FROM tbl WHERE title='T3' AND val>=4
)

其中tbl是您要搜索的表格 结果是3。 这是因为3符合这两个条件。

如果您想添加更多条件,请执行以下操作:

SELECT DISTINCT nr FROM tbl WHERE title='T2' AND val >=2
AND nr IN
(
SELECT nr FROM tbl WHERE title='T3' AND val>=4
)
AND nr IN (SELECT nr FROM tbl WHERE {new_criteria_1})
AND nr IN (SELECT nr FROM tbl WHERE {new_criteria_2})
AND nr IN (SELECT nr FROM tbl WHERE {new_criteria_3})
Where {new_criteria_1,2,3....n} are the new criteria in the WHERE clause you want to match.

答案 1 :(得分:1)

试试这个:

SELECT nr 
FROM table 
WHERE (title = 'T2' AND val >= 2) OR 
      (title = 'T3' AND val >= 4) 
GROUP BY nr 
HAVING COUNT(1) = 2