sql >> データベース >  >> RDS >> PostgreSQL

Pgで2つの単語が隣接している文を検索します

    より単純な解決策ですが、item.positionにギャップがない場合にのみ結果が得られます s:

    SELECT DISTINCT sentence.sentenceid 
      FROM sentence 
      JOIN item ON sentence.sentenceid = item.sentenceid
      JOIN word ON item.wordid = word.wordid
      JOIN item AS next_item ON sentence.sentenceid = next_item.sentenceid
                            AND next_item.position = item.position + 1
      JOIN word AS next_word ON next_item.wordid = next_word.wordid
     WHERE word.spelling = 'word1'
       AND next_word.spelling = 'word2'
    

    ウィンドウ関数 を使用したより一般的な解決策 :

    SELECT DISTINCT sentenceid
    FROM (SELECT sentence.sentenceid,
                 word.spelling,
                 lead(word.spelling) OVER (PARTITION BY sentence.sentenceid
                                               ORDER BY item.position)
            FROM sentence 
            JOIN item ON sentence.sentenceid = item.sentenceid
            JOIN word ON item.wordid = word.wordid) AS pairs
     WHERE spelling = 'word1'
       AND lead = 'word2'
    

    編集 :一般的な解決策(ギャップは許可されます)ですが、結合のみが含まれます:

    SELECT DISTINCT sentence.sentenceid
      FROM sentence 
      JOIN item ON sentence.sentenceid = item.sentenceid
      JOIN word ON item.wordid = word.wordid
      JOIN item AS next_item ON sentence.sentenceid = next_item.sentenceid
                            AND next_item.position > item.position
      JOIN word AS next_word ON next_item.wordid = next_word.wordid
      LEFT JOIN item AS mediate_word ON sentence.sentenceid = mediate_word.sentenceid
                                    AND mediate_word.position > item.position
                                    AND mediate_word.position < next_item.position
     WHERE mediate_word.wordid IS NULL
       AND word.spelling = 'word1'
       AND next_word.spelling = 'word2'
    


    1. WordPressクエリ:一致した行の順序順数?

    2. PHPは、mysqli_select_db()を使用した後でもデータベースが選択されていないと言います

    3. OracleSQL-外部キーに基づいて2つのテーブルをクエリします

    4. PostgreSQL-リレーションが見つかりません。