我想加入这些表(task_id和post_id),它将返回您在下面看到的所有内容。这很好但我接下来要做的是删除task_id的重复项,同时保留具有最高版本的项目。
我有2个这样的表:
项
ID title task_id project_id version
1 "Test" 123 456 1
2 "Test 2" 124 456 1
3 "Test 3" 125 456 1
4 "X 3.1" 125 456 1.1
5 "X 3.2" 125 456 1.2
任务
ID post_id meta_key meta_value
1 123 _completed 0
4 124 _completed 0
5 125 _completed 0
到目前为止我有这个SQL语句:
SELECT *
FROM items t0
INNER JOIN tasks AS t1
ON t0.task_id = t1.post_id
WHERE t1.meta_key = '_completed'
AND project_id = 456
返回:
ID title task_id project_id version ID post_id meta_key meta_value
1 "Test" 123 456 1 1 123 _completed 0
2 "Test 2" 124 456 1 1 124 _completed 0
3 "Test 3" 125 456 1 1 125 _completed 0
4 "X 3.1" 125 456 1.1 1 125 _completed 0
5 "X 3.2" 125 456 1.2 1 125 _completed 0
如何删除重复的task_id,但保留最高版本,以便表格为:
ID title task_id project_id version ID post_id meta_key meta_value
1 "Test" 123 456 1 1 123 _completed 0
2 "Test 2" 124 456 1 1 124 _completed 0
5 "X 3.2" 125 456 1.2 1 125 _completed 0
基本上我最接近ORDERing他们的BY版本和使用GROUP BY task_id,但显然SQL不允许你这样做。
有人能想出一个实现这个目标的好方法吗?
答案 0 :(得分:0)
根据相关帖子,我认为这应该有用。
SELECT *
FROM items t0
INNER JOIN tasks AS t1 ON t0.task_id = t1.post_id
INNER JOIN
(SELECT task_id, MAX(version) AS MaxVersion
FROM items
GROUP BY task_id) groupedt0
ON t0.task_id = groupedt0.task_id
AND t0.version = groupedt0.MaxVersion
AND project_id = 456
AND t1.meta_key = '_completed'
ORDER BY ID ASC
请参阅:How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?