3

像这样的桌子

桌子

|primary_key|  project | tag |
|    1      |    2     |  3  |
|    2      |    2     |  0  |
|    3      |    2     |  4  |
|    4      |    2     |  5  |
|    5      |    3     |  0  |
|    6      |    2     |  0  |

我想用标签'(3和4)或(0和4)和(5和0)'查询项目,在这个例子中,输出应该是项目2?我怎么能用 SQL 写这个?我尝试使用 phpmyadmin 生成几个结果,但没有按预期工作。

你们帮我真是太好了。我换个问题,如果条件复杂得多,查询可以来自表a、表b、表c吗?

4

4 回答 4

4

你想用聚合和一个having子句来做到这一点:

select project
from t
group by project
having sum(tag = 0 or tag = 3) > 0 and
       sum(tag = 4) > 0;

每个sum()表达式都在计算条件为真的行数。因此,这两个条件是说“至少有一行标签 = 0 或 3,并且至少有一行标签 = 4”。

于 2013-09-12T14:24:30.033 回答
2

您可以将表连接到自身,并检查标签为 3/0 的每一行是否还有另一行标签为 4。

SELECT DISTINCT a.project
FROM table a, table b
WHERE a.project= b.project AND
    ( a.tag = 3 AND b.tag = 4 ) OR 
    ( a.tag = 0 AND b.tag = 4 ) 

根据更新的问题更新。

于 2013-09-12T14:20:32.653 回答
1

尝试这个:

SELECT distinct
    a.project
from
    `table` a
        join
    `table` b ON b.project = a.project and b.tag = 4
where
    a.tag in (0 , 3)

SQL 小提琴演示

于 2013-09-12T14:42:05.463 回答
0

这将是最近编辑的查询(3 and 4) or (0 and 4) and (5 and 0)不确定是否是((3 and 4) or (0 and 4)) and (5 and 0)OR(3 and 4) or ((0 and 4) and (5 and 0))所以我选择了前者。

SELECT
    project
FROM
    t
GROUP BY
    project
HAVING
    (sum(tag = 3 AND tag = 4) > 0 OR
    sum(tag = 0 AND tag = 4) > 0) AND
    sum(tag = 5 AND tag = 0)
于 2013-09-12T14:40:17.637 回答