且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL在表的两个副本之间使用WHERE子句依赖关系留下自连接

更新时间:2022-12-28 16:10:06

word_number + 1 要求移到 LEFT JOIN 中.

Move the word_number + 1 requirement into the LEFT JOIN.

SELECT
  s1.word word1, s2.word word2
FROM
  sentence_words s1
LEFT JOIN
  sentence_words s2
    ON  s2.sentence_id = s1.sentence_id
    AND s2.word_number = s1.word_number + 1
WHERE
  s1.word_number = my_start_number

NECRO

虽然以上修复了 LEFT JOIN 的使用,但我建议根本不要使用连接...

Although the above fixes the use of LEFT JOIN, I would suggest not using joins at all...

SELECT
  sentence_id,
  MAX(CASE WHEN pos = 0 THEN word END)   AS word1,
  MAX(CASE WHEN pos = 1 THEN word END)   AS word2
FROM
(
  SELECT
    sentence_id,
    word_number - MY_START_NUMBER   AS pos,
    word
  FROM
    sentence_words
)
  AS offset_sentence_words
WHERE
  pos IN (0, 1)
GROUP BY
  sentence_id