下面我在图像中有以下结构。
查询的目的是返回表表达式中不存在的短语。为了最初获得解决方案,我不得不使用两个查询。
第一个查询返回一个计数器,该计数器在表格表达式中包含几个单词的短语。在having子句的分组中设置了一个限制。例如十五岁。
SELECT ex.phrase_id, count(ex.phrase_id) as total FROM Expressions ex
GROUP BY ex.phrase_id
HAVING COUNT(ex.phrase_id) < 15
ORDER BY total desc;
在第二个查询中执行一个子查询,考虑不在表格中的所有单词。可以看出,此查询使用phrase_id 6和5到子句限制的固定值。当然,这些值适用于每个变量。
SELECT all_data.id as 'word_id', all_data.name as 'word_name', all_data.`phrase_id` FROM
(
SELECT
wo.*,
'6' AS phrase_id
FROM Words wo
WHERE wo.id NOT IN(
SELECT ex.word_id FROM Expressions ex WHERE ex.phrase_id = 6
) LIMIT 5 ) AS all_data;
以下是使用java语言的实现代码。
public void findExpressions() {
StringBuilder query_phrases_words_not_group = new StringBuilder( 50 );
query_phrases_words_not_group.append( "SELECT ex.phrase_id, count(ex.phrase_id) as total FROM Expressions ex " );
query_phrases_words_not_group.append( "GROUP BY ex.phrase_id " );
query_phrases_words_not_group.append( "HAVING COUNT(ex.phrase_id) < 15 " );
query_phrases_words_not_group.append( "ORDER BY total desc; " );
List<Map<String, Object>> rows = jdbcTemplate.queryForList( query_phrases_words_not_group.toString() );
for( Map row : rows ){
Long phrase_id = ((BigInteger) row.get( "phrase_id" )).longValue();
Long total = (Long.valueOf(3000) - (Long) row.get( "total" ));
StringBuilder query_data_group = new StringBuilder(50);
query_data_group.append( "SELECT all_data.id as 'word_id', all_data.name as 'word_name', all_data.`phrase_id` FROM " );
query_data_group.append( "( " );
query_data_group.append( "SELECT " );
query_data_group.append( " wo.*, " );
query_data_group.append( phrase_id ).append( " AS phrase_id " );
query_data_group.append( " FROM Words wo " );
query_data_group.append( "WHERE wo.id NOT IN( " );
query_data_group.append( " SELECT ex.word_id FROM Expressions ex WHERE ex.phrase_id = " ).append( phrase_id );
query_data_group.append( ") LIMIT 5 ) AS all_data");
List<Map<String, Object>> data_rows = jdbcTemplate.queryForList( query_data_group.toString() );
for( Map data_row : data_rows ){
Long word_id = ((BigInteger) data_row.get( "word_id" )).longValue();
String word = (String) data_row.get( "word_id" );
phrase_id = ((BigInteger) data_row.get( "phrase_id" )).longValue();
}
}
}
我想在这里与大家分享一个更好的方法,只对数据库进行一次查询。我想预期的最终结果就像图像一样。