这是我的两张 table 。我想删除两个表(zipkin_annotations
、zipkin_spans
)中所有带有trace_id且超过5天的行
CREATE TABLE IF NOT EXISTS zipkin_spans (
`trace_id_high` BIGINT NOT NULL DEFAULT 0 COMMENT 'If non zero, this means the trace uses 128 bit traceIds instead of 64 bit',
`trace_id` BIGINT NOT NULL,
`id` BIGINT NOT NULL,
`name` VARCHAR(255) NOT NULL,
`parent_id` BIGINT,
`debug` BIT(1),
`start_ts` BIGINT COMMENT 'Span.timestamp(): epoch micros used for endTs query and to implement TTL',
`duration` BIGINT COMMENT 'Span.duration(): micros used for minDuration and maxDuration query'
) ENGINE=InnoDB ROW_FORMAT=COMPRESSED CHARACTER SET=utf8 COLLATE utf8_general_ci;
ALTER TABLE zipkin_spans ADD UNIQUE KEY(`trace_id_high`, `trace_id`, `id`) COMMENT 'ignore insert on duplicate';
CREATE TABLE IF NOT EXISTS zipkin_annotations (
`trace_id_high` BIGINT NOT NULL DEFAULT 0 COMMENT 'If non zero, this means the trace uses 128 bit traceIds instead of 64 bit',
`trace_id` BIGINT NOT NULL COMMENT 'coincides with zipkin_spans.trace_id',
`span_id` BIGINT NOT NULL COMMENT 'coincides with zipkin_spans.id',
`a_key` VARCHAR(255) NOT NULL COMMENT 'BinaryAnnotation.key or Annotation.value if type == -1',
`a_value` BLOB COMMENT 'BinaryAnnotation.value(), which must be smaller than 64KB',
`a_type` INT NOT NULL COMMENT 'BinaryAnnotation.type() or -1 if Annotation',
`a_timestamp` BIGINT COMMENT 'Used to implement TTL; Annotation.timestamp or zipkin_spans.timestamp',
`endpoint_ipv4` INT COMMENT 'Null when Binary/Annotation.endpoint is null',
`endpoint_ipv6` BINARY(16) COMMENT 'Null when Binary/Annotation.endpoint is null, or no IPv6 address',
`endpoint_port` SMALLINT COMMENT 'Null when Binary/Annotation.endpoint is null',
`endpoint_service_name` VARCHAR(255) COMMENT 'Null when Binary/Annotation.endpoint is null'
) ENGINE=InnoDB ROW_FORMAT=COMPRESSED CHARACTER SET=utf8 COLLATE utf8_general_ci;
ALTER TABLE zipkin_annotations ADD UNIQUE KEY(`trace_id_high`, `trace_id`, `span_id`, `a_key`, `a_timestamp`) COMMENT 'Ignore insert on duplicate';
通过下面的查询,我可以从 zipkin_spans
中检索超过 5 天的行。
SELECT count(*) from zipkin_spans
WHERE FROM_UNIXTIME(zipkin_spans.start_ts/1000000) < DATE_SUB(NOW(), INTERVAL 5 DAY)
但我希望 zipkin_annotations
中的行具有相同的traceId。请就此提出建议(带查询)。
最佳答案
您可以使用子查询来完成此操作,如下所示:
SELECT * FROM zipkin_annotations
WHERE trace_id IN (SELECT trace_id from zipkin_spans
WHERE FROM_UNIXTIME(zipkin_spans.start_ts/1000000) < DATE_SUB(NOW(), INTERVAL 5 DAY))
内部查询根据您所需的条件从 zipkin_spans 中获取所有 traceId,外部查询仅从 zipkin_annotations 中获取记录那些traceId。
上面的查询当然只会选择行,你可以替换SELECT
与 DELETE
删除行。
另一个建议是,在设计架构时,您可以使用 Foreign key
为了您的目的。有一个名为 Delete on cascade
的选项,这将从 zipkin_annotations 中删除所有具有从 zipkin_spans 中删除的 traceId 的行。
关于mysql - 如何在一张表中使用 WHERE 子句删除 2 个表行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48820507/