我有一个包含以下列的表:
id, name, domain, added, is_verified
1, "First Google", "google.com", DATE(), 1
2, "Second Google", "google.com", DATE(), 1
3, "Third Google", "google.com", DATE(), 1
4, "First disney", "disney.com", DATE(), 1
5, "Second disney", "disney.com", DATE(), 1
6, "Third disney", "disney.com", DATE(), 0
7, "First example", "example.com", DATE(), 0
8, "Second example", "example.com", DATE(), 0
以下要求:
SELECT domain FROM mytable WHERE domain NOT IN
(SELECT domain FROM mytable WHERE is_verified = 1 GROUP BY domain)
GROUP BY domain ORDER BY added DESC;
此请求背后的主要思想是将所有没有domain
的{{1}}设置为true。
在上面的例子中,这只会返回“example.com”一次。
请求运行良好,但需要时间来执行(我有数千个条目)。还有其他方法可以使这个请求更快更有效吗?
答案 0 :(得分:2)
您可以LEFT JOIN
使用NULL
支票:
SELECT T1.Domain
FROM mytable T1
LEFT JOIN mytable T2 ON T2.domain = T1.domain AND T2.is_verified = 1
WHERE T2.ID IS NULL
使用给定数据执行示例:
DECLARE @TESTDOMAIN TABLE (id int, name varchar(100), domain varchar (100), added datetime, is_verified bit)
insert into @testdomain (id, name, domain, added, is_verified)
SELECT 1, 'First Google', 'google.com', GETDATE(), 1 UNION
SELECT 2, 'Second Google', 'google.com', GETDATE(), 1 UNION
SELECT 3, 'Third Google', 'google.com', GETDATE(), 1 UNION
SELECT 4, 'First disney', 'disney.com', GETDATE(), 1 UNION
SELECT 5, 'Second disney', 'disney.com', GETDATE(), 1 UNION
SELECT 6, 'Third disney', 'disney.com', GETDATE(), 0 UNION
SELECT 7, 'First example', 'example.com', GETDATE(), 0 UNION
SELECT 8, 'Second example', 'example.com', GETDATE(), 0
SELECT T1.Domain
FROM @TESTDOMAIN T1
LEFT JOIN @TESTDOMAIN T2 ON T2.domain = T1.domain AND T2.is_verified = 1
WHERE T2.ID IS NULL
答案 1 :(得分:1)
SELECT domain
FROM mytable
group by domain
having max(is_verified) = 0
ORDER BY max(added) DESC
我添加了order by
子句。您必须决定要为每个域采用哪个added
记录。我选择了域的最大附加值。
答案 2 :(得分:-1)
为什么必须使用子选择?不会产生相同的结果吗?
package ls2.repositories;
import org.springframework.data.neo4j.repository.GraphRepositoryImpl;
import org.springframework.data.neo4j.template.Neo4jOperations;
import ls2.models.User;
public class UserOpImpl extends GraphRepositoryImpl<User> implements UserOp {
public UserOpImpl(Neo4jOperations neo4jOperations) {
super(User.class, neo4jOperations);
}
}