PostgreSQL
 sql >> Teknologi Basis Data >  >> RDS >> PostgreSQL

Temukan kalimat dengan dua kata yang saling berdekatan di Pg

Solusi yang lebih sederhana, tetapi hanya memberikan hasil, bila tidak ada celah di 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'

Solusi yang lebih umum, menggunakan fungsi jendela :

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'

Sunting :Juga solusi umum (celah diperbolehkan), tetapi hanya dengan gabungan:

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. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Bagaimana wadah OpenShift dapat mempelajari ID gambarnya?

  2. Postgres 9.1 vs Mysql 5.6 InnoDB?

  3. Bergabunglah dengan 2 tabel di mana dua set angka tumpang tindih dalam kolom yang bergabung

  4. Cara membersihkan komentar dari file sql mentah

  5. Bagaimana cara menentukan tipe kolom untuk CTE (Common Table Expressions) di PostgreSQL?