【问题标题】:MySQL Joins not working as requiredMySQL 连接未按要求工作
【发布时间】:2015-11-29 20:51:20
【问题描述】:

我有两张桌子。

表 A:

root_id, root_text

表 B:

word_id , word_text,root_text

现在Table B 的一些记录有可能在Table A 中不存在的root_texts。

因此,我正在尝试使用左连接。

select *
from   A a , B b
where  a.root_text=+b.root_text

我只得到匹配root_text的记录。

如果我使用新方法

Select
  *
from
  A left join B on a.root_text= b.root_text 

我得到了很多额外的记录。我正在使用 MySQL 5.6.1.7

更新:

http://sqlfiddle.com/#!9/7b32a/2

查询我正在运行

select * from   word_detail w left  join roots r
on r.root_text =w.root
and w.surah_no=1
and w.verse_no=1
and w.word_no=1

我做错了什么?

作为结果,您会看到很多不需要的记录。过滤器 verse_no , word_no 不起作用。

更新

问题是在左连接之后我们必须使用 where

select * from   word_detail w left  join roots r
    on r.root_text =w.root
    where w.surah_no=1
    and w.verse_no=1
    and w.word_no=1

【问题讨论】:

    标签: mysql sql select left-join


    【解决方案1】:

    如果您想要 TableB 中不存在于表 A 中的所有记录,您应该使用这个:

    Select *
    from
      B left join A
      on a.root_text= b.root_text
    where
      a.root_text is null
    

    或者如果您想要相反的 - 表 A 中不存在于表 B 上的所有记录:

    Select *
    from
      A left join B
      on a.root_text= b.root_text
    where
      b.root_text is null
    

    顺便说一句,这不是 MySQL 上的左连接:

    select * from A a , B b where a.root_text=+b.root_text
    

    但会产生一个简单的 INNER JOIN

    【讨论】:

    • 请查看我更新的问题。我在 MySQL fiddle 中创建了 schemar。 – Makky 刚刚编辑
    • @Makky 左联接将返回左侧表中的所有行,并且仅返回右侧表中联接成功的行。如果您只想要左侧没有相应记录的行,则必须添加 where tableright.column is null
    • @Makky 您可以在 r.root_text 为空的地方添加(根文本是连接右侧的列,它位于 ON 子句中,因此只有在没有对应关系时才会为空)
    • 问题是我在加入之后使用 AND ......如果我使用 WHERE ......谢谢。
    【解决方案2】:

    += 运算符不是标准 SQL,而是特定于 Oracle RDBMS,因此它无法在 MySQL 上按预期工作。

    LEFT JOIN 语法是正确的,“许多额外记录”源于您表中的数据。您可能希望使用某种WHERE 作为过滤器或聚合来对结果集进行分组,使其更易于管理。

    【讨论】:

    • 请查看我更新的问题。我在 MySQL fiddle 中创建了 schemar。
    【解决方案3】:

    您的第一个示例是内部联接,它解释了为什么您没有获得与离开时一样多的结果。左连接也可以认为是左外连接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-27
      • 2015-06-17
      • 1970-01-01
      • 2011-06-02
      • 2012-03-31
      • 1970-01-01
      • 2018-09-12
      • 1970-01-01
      相关资源
      最近更新 更多