我想在data的1-3中得到所有不在id的6中的id
我使用id是为了简单起见,但我实际上使用的是时间戳。

CREATE TABLE test (
  id bigint(20) NOT NULL AUTO_INCREMENT,
  data varchar(3) NOT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

INSERT INTO test (id, data) VALUES
(1, 'abc'),
(2, 'def'),
(3, 'ghi'),
(4, 'jkl'),
(5, 'mno'),
(6, 'pqr'),
(7, 'def'),
(8, 'vxw'),
(9, 'yz');

我试过的几十个问题中的一个。
SELECT
  t1.data t1_data,
  t2.data t2_data
FROM test t1
JOIN test t2
  ON t2.id BETWEEN 1 AND 3
    AND t1.id > 6
    AND t1.data <> t2.data

所以我想得到这个结果:
+----------+
|   data   |
+----------+
|   abc    |
|   ghi    |
+----------+

最佳答案

SELECT t1.data AS t1_data
FROM test t1
WHERE t1.id BETWEEN 1 AND 3
AND NOT EXISTS(
  SELECT *
  FROM test t2
  WHERE t2.data = t1.data
  AND  t2.id > 6
  );

关于mysql - 将表联接到自身并选择不匹配的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19780251/

10-16 22:08