在MySQL中选择具有distinct和condition的所有行

时间:2017-09-16 17:31:42

标签: mysql row distinct

大家好我是mySQL的新手,我的查询有问题。我试图写一些查询从表中获取所有记录,如果我有两个相同日期的记录,我需要只记录这两个有manual_selection = 1的记录。

所以结果应该是我的表中的所有记录,除了id = 1401和id = 1549

my table

我试图结合如何获得这样的记录:

SELECT * FROM project.score WHERE project_id = 358 
AND crawled_at IN(SELECT crawled_at FROM project.score WHERE project_id = 358 
AND manual_selection = 1 GROUP BY crawled_at)
ORDER BY crawled_at;      

SELECT * FROM project.score WHERE project_id = 358 
GROUP BY crawled_at HAVING manual_selection = 1;  

但是我的所有方式总是只获得带有manual_selection = 1的行。我不知道在manual_selection = 1的情况下如何区分具有重复“crawled_at”的行?有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

试试这个:

select main.id, main.project_id, main.crawled_at, main.score, main.manual_selection
from dcdashboard.moz_optimization_keywords as main
left join dcdashboard.moz_optimization_keywords as non_manual_selection on non_manual_selection.crawled_at = main.crawled_at and non_manual_selection.manual_selection != 1
group by main.crawled_at;

数据集来自问题的结果:

+------+------------+---------------------+-------+------------------+
| id   | project_id | crawled_at          | score | manual_selection |
+------+------------+---------------------+-------+------------------+
|  807 |        360 | 2016-02-06 00:00:00 |    76 |                0 |
| 1001 |        360 | 2016-02-20 00:00:00 |    76 |                0 |
|  223 |        360 | 2016-11-28 00:00:00 |    76 |                0 |
|  224 |        360 | 2016-12-05 00:00:00 |    76 |                0 |
|  670 |        360 | 2016-12-19 00:00:00 |    76 |                0 |
| 1164 |        360 | 2017-04-19 00:00:00 |    78 |                1 |
| 1400 |        360 | 2017-09-13 00:00:00 |    96 |                1 |
| 1548 |        360 | 2017-09-15 00:00:00 |    96 |                1 |
+------+------------+---------------------+-------+------------------+
8 rows in set (0.00 sec)