[英]SQL If records are repetitive select the one with the max id
I have a query that returns older versions of some records (due to bad database design) and i try to get only the newest ones. 我有一个查询返回一些记录的旧版本(由于数据库设计不好),我试图只获得最新的。 So i try to get the ones with Max Id's but query is complicated and there are lots of records. 所以我试着用Max Id的那些,但查询很复杂,并且有很多记录。 So subselect queries like this wont work: 所以这样的subselect查询不会起作用:
SELECT row
FROM table
WHERE id=(
SELECT max(id) FROM table
)
And here's my query. 这是我的疑问。 By the way my company is using Testlink, if you're familiar with it and you have a better solution for this, it would be appreciated. 顺便说一下,我的公司正在使用Testlink,如果您熟悉它并且您有更好的解决方案,那么我们将不胜感激。
SELECT req_doc_id, scope,nh.parent_id,nh.id
FROM (SELECT nh.id, req_doc_id,doc_id FROM nodes_hierarchy nh,
req_specs r1, requirements r2
WHERE nh.parent_id = r1.id AND nh.id = r2.id
AND (r1.doc_id LIKE '%BlaBla%' OR r1.doc_id LIKE '%Tralala%'))
AS t1, nodes_hierarchy nh, req_versions r1
WHERE t1.id = nh.parent_id AND nh.id = r1.id
And resultset is 结果集是
NAME..................ID
____
BlaBla1..............163
BlaBla1..............190
BlaBla2..............173
Tralala..............15
Tralala2.............26
Tralala2.............19
What I want is: 我想要的是:
NAME..................ID
____
BlaBla1..............190
BlaBla2..............173
Tralala..............15
Tralala2.............26
SELECT TB.NAME,TB.ID FROM TABLE TB
INNER JOIN
(
SELECT NAME,MAX(ID) ID FROM TABLE GROUP BY NAME
)INNERTABLE ON INNERTABLE.ID=TB.ID
Try above query. 尝试以上查询。
Here you go: 干得好:
SELECT Name,Notes
FROM (select nh.id ,req_doc_id as Name, scope as Notes from
(select nh.id,req_doc_id,doc_id from nodes_hierarchy nh ,
req_specs r1, requirements r2
where nh.parent_id = r1.id and nh.id = r2.id
and ( r1.doc_id like '%Tralala%'
or r1.doc_id like '%BlaBla' ) )
as t1,
nodes_hierarchy nh, req_versions r1
where t1.id = nh.parent_id and nh.id = r1.id ) AS TABLO
INNER JOIN(
SELECT MAX(nh.id) ID ,scope FROM (select nh.id,req_doc_id,doc_id from nodes_hierarchy nh ,
req_specs r1, requirements r2
where nh.parent_id = r1.id and nh.id = r2.id
and (r1.doc_id like '%Tralala%'
or r1.doc_id like '%BlaBla' ) )
as t1, nodes_hierarchy nh, req_versions r1 where t1.id = nh.parent_id and nh.id = r1.id GROUP BY req_doc_id)
INNERTABLE on INNERTABLE.ID = TABLO.ID;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.