这是我当前的查询。
SELECT *
FROM covered_panel_table
WHERE panel_id = "2" AND
date_added <= "2019-03-22"
ORDER BY gene ASC, genes_covered_by_panel_id ASC
我想添加到查询中,如果有多个条目带有示例panel_id,基因和外显子,请选择一个小于或等于报告日期的条目,或者如果两者都较大,请选择最新的条目。
描述Covered_panel_table;
+---------------------------+-------------+------+-----+
| Field | Type | Null | Key |
+---------------------------+-------------+------+-----+
| covered_panel_id | int(11) | NO | PRI |
| panel_id | int(11) | YES | |
| gene | varchar(7) | YES | |
| exon | varchar(17) | YES | |
| accession_num | varchar(16) | YES | |
| date_added | date | YES | |
+---------------------------+-------------+------+-----+
已更新:
示例数据:
+------------------+----------+--------+-----------------+----------------+------------+
| covered_panel_id | panel_id | gene | exon | accession_num | date_added |
+------------------+----------+--------+-----------------+----------------+------------+
| 2 | 2 | ASXL1 | 12 | NM_015338.5 | 2017-09-22 |
| 245 | 2 | BCOR | all | NM_001123385.1 | 2019-03-22 |
| 3 | 2 | BCOR | all | NM_017745.5 | 2017-09-22 |
| 4 | 2 | BRAF | 15 | NM_004333.4 | 2017-09-22 |
| 7 | 2 | CBL | 8, 9 | NM_005188.3 | 2019-03-18 |
| 6 | 2 | DNMT3a | all | NM_022552.4 | 2019-03-25 |
+------------------+----------+--------+-----------------+----------------+------------+
预期结果
+------------------+----------+--------+-----------------+----------------+------------+
| covered_panel_id | panel_id | gene | exon | accession_num | date_added |
+------------------+----------+--------+-----------------+----------------+------------+
| 2 | 2 | ASXL1 | 12 | NM_015338.5 | 2017-09-22 |
| 245 | 2 | BCOR | all | NM_001123385.1 | 2019-03-22 |
| 4 | 2 | BRAF | 15 | NM_004333.4 | 2017-09-22 |
| 7 | 2 | CBL | 8, 9 | NM_005188.3 | 2019-03-18 |
+------------------+----------+--------+-----------------+----------------+------------+
答案 0 :(得分:3)
https://www.db-fiddle.com/f/uiGXVQ85yYez4YdEF12Mt5/0
SELECT cpt.*
FROM covered_panel_table cpt
LEFT JOIN covered_panel_table cpt1
ON cpt.panel_id = cpt1.panel_id
AND cpt.gene = cpt1.gene
AND cpt.exon = cpt1.exon
AND cpt.date_added < cpt1.date_added
WHERE cpt.panel_id = "2" AND
cpt.date_added <= "2019-03-22"
AND cpt1.covered_panel_id IS NULL
ORDER BY cpt.gene ASC
由于未为表格定义该列,因此我从genes_covered_by_panel_id ASC
表单中删除了ORDER BY
。