存在于具有重复字段的同一表上的其他行中

时间:2016-07-19 17:07:13

标签: mysql

我有一个表格结构:

CREATE TABLE `table1` (
  `pk_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `field1` varchar(16) NOT NULL,
  `field2` char(1) DEFAULT NULL,
  `field3_date` datetime DEFAULT NULL,
  PRIMARY KEY (`pk_id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

field1会有重复的地方。我正在尝试在特定月份的A中查询Bfield2的所有行,其中同一个表中存在具有相同field1的行或行但Zfield2。我已将此解释为以下查询:

SELECT * FROM table1
WHERE (field2='A' or field2='B') AND
MONTH(field3_date)=MONTH('2016-06-01') AND
EXISTS
    (
        SELECT field1 FROM table1 AS temp_table
        WHERE table1.field2='Z' AND table1.field1=temp_table.field1
    )
ORDER BY field3_date DESC;

虽然我已经确认许多实例符合条件,但我没有返回任何行。我在子查询中尝试了不使用AND table1.field1=temp_table.field1并获得相同的结果。关于什么可以纠正我的查询的任何建议或指示?热烈的问候,

编辑:此处提供的虚拟数据和预期输出示例:

https://docs.google.com/spreadsheets/d/1-dSXR_sK71ZSrzRpAsfm0VBEP9EDDKTtcMRXOeclwNs/edit?usp=sharing

第二次编辑:以可用格式添加模拟数据:

INSERT INTO Table1
    (`pk_id`, `field1`, `field2`, `field3_date`)
VALUES
    (10000000000000000001, 'SFCAVLDLYCQQFPHB', 'A', '2016-06-01 00:00:00'),
    (10000000000000000002, 'BP3RJZCWQFXS32TS', 'B', '2016-06-02 00:00:00'),
    (10000000000000000003, 'PVR2HEA6VFXYVFVV', 'A', '2016-06-03 00:00:00'),
    (10000000000000000004, 'G7MDHGYVUUELJZCY', 'B', '2016-06-04 00:00:00'),
    (10000000000000000005, 'PVR2HEA6VFXYVFVV', 'Z', '2016-06-05 00:00:00'),
    (10000000000000000006, 'NC3KNPPGDH6JTCEW', 'A', '2016-06-06 00:00:00'),
    (10000000000000000007, '4TYFQNKSRYEJXABH', 'A', '2016-06-07 00:00:00'),
    (10000000000000000008, 'BP3RJZCWQFXS32TS', 'Z', '2016-06-08 00:00:00'),
    (10000000000000000009, 'EGUR5CUBYRQZ6286', 'B', '2016-06-09 00:00:00'),
    (10000000000000000010, 'SQWKPRYJEJDMZ8Y3', 'B', '2016-06-10 00:00:00')
;

1 个答案:

答案 0 :(得分:1)

这个怎么样?

SELECT t2.*
FROM   table1 t1
JOIN   table1 t2
ON     t2.field2 = 'Z' AND
       t2.field1 = t1.field1 AND
       t2.pk_id <> t1.pk_id
WHERE t1.field2 IN ('A', 'B') AND
      MONTH(t1.field3_date)=MONTH('2016-06-01')

t1是您的原始表格; t2是您的副本。 t1.pk_idt2.pk_id的比较可确保t1不会加入自身。实际上,这种比较并不是严格要求的(因为t2.field2将是'Z'而t1.field2将是'A'或'B',但如果您想要使用不同的修改查询,这是一个很好的保护措施选择标准以后。