我需要将左表与右表连接起来,并保留所有左表行,即使右表不匹配也是如此。 ...标准的左联接。

仅包括符合条件的左表行。

仅包括符合条件的右表行。如果未找到,则在连接中使用null。

如果不为null,则按右表中的列排序,但如果为null,则不要丢失条目。

在伪SQL中,我想要

(
    select
        *
    from
        work_item
    where
        work_item.id_work_item_queue = 5
) as t1

(
    select
        *
    from
        ai_guess
    where
        ai_guess.AI_Guess_Date = '2019:08:09:19:49:02'
) as t2

select
    t1.*,
    t2.*
from
    t1
    left join t2 on t1.id_word_crop = t2.id_word_crop
ORDER BY
    ai_guess.text


我得出的解决方案是

SELECT
    work_item.id_work_item,
    work_item.id_word_crop,
    ai_guess.text

FROM
    work_item
    LEFT JOIN ai_guess ON
    work_item.id_word_crop = ai_guess.id_word_crop

WHERE
    work_item.id_work_item_queue = 5
    AND
    ai_guess.AI_Guess_Date = '2019:08:09:19:49:02'

ORDER BY
    ai_guess.text


这产生

id_work_item, id_word_crop, text
'4', '224343', 'eie'
'3', '224342', 'geüichrt'
'2', '224341', 'rschaunig'
'6', '224345', 'VSnge'


但它丢失了,并从左表中输入

id_work_item, id_word_crop
'5', '224344'


左表包含

SELECT
    id_work_item,
    id_word_crop
FROM
    work_item
where
    id_work_item_queue = 5


    id_work_item, id_word_crop
    '2', '224341'
    '3', '224342'
    '4', '224343'
    '5', '224344'
    '6', '224345'


右边的表没有匹配项,因此删除了左边的条目,但我想保留左边的条目。

SELECT
    *
FROM
    ai_guess
where
    id_word_crop = 224344


返回null

最佳答案

ai_guess表上的条件从WHERE移到ON子句:

SELECT
    work_item.id_work_item,
    work_item.id_word_crop,
    ai_guess.text
FROM work_item
LEFT JOIN ai_guess
    ON work_item.id_word_crop = ai_guess.id_word_crop AND
       ai_guess.AI_Guess_Date = '2019:08:09:19:49:02'
WHERE
    work_item.id_work_item_queue = 5
ORDER BY
    ai_guess.text;


现在发生的是联接生成所需的中间结果,但是WHERE子句过滤掉丢失的记录,因为其猜测日期不匹配。通过在连接条件中放置此限制,可以防止过早删除该记录。

关于mysql - 左联接,其中左表列=某些内容或为null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57797287/

10-10 00:04