针对同一列的MySQL AND运算符

时间:2016-08-26 06:14:08

标签: mysql

我在sql中有一个名为TagQuestion的表,其中包含idtagIdquestionId等字段。

以下是表格中的数据:

+---------------------+
|id |tagId |QuestionId|
+---------------------+    
|2  |1     |2         |
|4  |1     |3         |
|6  |2     |3         |
+---------------------+

我想从tagId=1以及tagId=2

的表格中查询问题ID

我正在尝试查询 -

select * from TagQuestion where (tagId=1 AND tagId=2)

但它没有返回任何东西。

你能帮我解决这个问题吗?

4 个答案:

答案 0 :(得分:2)

获得此类问题的简便方法是使用group byhaving

select questionId
from TagQuestion
where tagId in (1, 2)
group by questionId
having count(distinct tagId) = 2;

答案 1 :(得分:1)

尝试此查询:

select * from TagQuestion where tagId IN (1,2)

您的查询正在检查tagId=1 AND tagId=2是否对同一记录不可能。要获取具有tagId=1tagId=2的记录,您需要使用IN运算符。

答案 2 :(得分:0)

你应该尝试:

SELECT * FROM TagQuestion WHERE tagId IN (1,2);

你的查询where (tagId = 1 and tagId = 2)检查tagId每行的时间是否有1和2的值...所以它不输出任何东西它总是错误的...另一种选择是替换你的{ {1}}至AND

答案 3 :(得分:0)

您声称该列应该同时为1 2 - 根据逻辑规律(Boolean Algebra),这总是 false - 因此它总是返回0行。

我想您打算返回TagID包含1 2的行,如果是这样,替换 AND < / strong>在您的查询中 OR

select * from TagQuestion where (tagId=1 OR tagId=2)