我有一个表格结构:
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
中查询B
或field2
的所有行,其中同一个表中存在具有相同field1
的行或行但Z
为field2
。我已将此解释为以下查询:
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')
;
答案 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_id
和t2.pk_id
的比较可确保t1
不会加入自身。实际上,这种比较并不是严格要求的(因为t2.field2
将是'Z'而t1.field2
将是'A'或'B',但如果您想要使用不同的修改查询,这是一个很好的保护措施选择标准以后。