在1列中搜索where和statement

时间:2014-01-10 01:05:25

标签: mysql sql

我正在尝试使用where语句搜索列。所以我的数据库看起来像这样:

CREATE TABLE test
    (
 zID varchar(20), 
 tID varchar(30)
 );

INSERT INTO test
(zID, tID)
VALUES
('1','1'),
('1','2'),
('2','1'),
('2','2'),
('3','1');

然后我使用以下SQL语句进行搜索:

SELECT * from test where tID = 1 and tID = 2

所以,当我把这个查询应该返回12而不是3所有zIDs时,我尝试使用in但这将返回所有zIDs。这不是我想要的,所以我的问题是如何用和搜索?

而是使用类似于in的{​​{1}}。

继承人fiddle

1 个答案:

答案 0 :(得分:1)

这样做的一个方法是使用COUNT()聚合,通过DISTINCT tID子句进行过滤,验证每个zIDIN()的总数是否等于2

SELECT zID
FROM test
/* Limit rows to tID 1,2
WHERE tID IN (1,2)
GROUP BY zID
/* Verify that the total DISTINCT number of tID
   per group of zID is 2, that way you know *both*
   values are present.
   Substitute the total number of values in the IN() for the comparison
   against COUNT() (substitute for 2 here) to do this dynamically
*/
HAVING COUNT(DISTINCT tID) = 2

The updated fiddle

以上内容仅返回zID,但可以使用JOIN或其他IN()子句对其进行展开以返回所有列。

/* Get all columns for the zID returned inside */
SELECT * FROM test WHERE zID IN (
  SELECT zID
  FROM test
  WHERE tID IN (1,2)
  GROUP BY zID
  HAVING COUNT(DISTINCT tID) = 2
)

或使用JOIN

SELECT test.*
FROM
  test
  INNER JOIN (
      SELECT zID
      FROM test
      WHERE tID IN (1,2)
      GROUP BY zID
      HAVING COUNT(DISTINCT tID) = 2
    ) tz ON test.zID = tz.zID