来自 MYSQL table A 的 Return 行 table_A.col_1 = table_b.col_2 不使用左外连接?
Return rows from MYSQL table A where table_A.col_1 = table_b.col_2 without using a left outer join?
在具有两个 table 和 table_A
的 MySQL 数据库中,我想 return 从 table_A
中选择行列与 table_B
中的值进行比较。下面的错误行总结了这个想法:
SELECT col_1, col_2, col_3 FROM table_A where table_A.col_1 = table_B.col_2;
我不想要 table_B
中的任何元素。
为什么我不能使用左外连接:我已经尝试过使用左外连接,如此处所示(https://blog.codinghorror.com/a-visual-explanation-of-sql-joins/)但是数据库抱怨列名不明确,无法更改数据库中的 table 列名。
我想要 table_A
中的行 col1
可以在 table_B(col_2)
中找到,您可以使用 exists
:
select a.col_1, a.col_2, a.col_3
from table_A a
where exists (select 1 from table_B b where b.col_2 = a.col_1);
如果您想要 table_B
中不存在的行,则只需将 exists
更改为 not exists
。
请注意,我在列名称前加上它们所属的 table 的(别名)。这称为 限定 列,这是避免在尝试 join
.
时似乎遇到的不明确列名问题的方法。
如果列名不明确,请限定它们,例如
select table_A.col_1, table_A.col_2, table_A.col_3
from table_A
join table_B on table_A.col_1 = table_B.col_2
或者为简洁起见,您可以为表分配一个别名:
select a.col_1, a.col_2, a.col_3
from table_A a
join table_B b on a.col_1 = b.col_2
在具有两个 table 和 table_A
的 MySQL 数据库中,我想 return 从 table_A
中选择行列与 table_B
中的值进行比较。下面的错误行总结了这个想法:
SELECT col_1, col_2, col_3 FROM table_A where table_A.col_1 = table_B.col_2;
我不想要 table_B
中的任何元素。
为什么我不能使用左外连接:我已经尝试过使用左外连接,如此处所示(https://blog.codinghorror.com/a-visual-explanation-of-sql-joins/)但是数据库抱怨列名不明确,无法更改数据库中的 table 列名。
我想要 table_A
中的行 col1
可以在 table_B(col_2)
中找到,您可以使用 exists
:
select a.col_1, a.col_2, a.col_3
from table_A a
where exists (select 1 from table_B b where b.col_2 = a.col_1);
如果您想要 table_B
中不存在的行,则只需将 exists
更改为 not exists
。
请注意,我在列名称前加上它们所属的 table 的(别名)。这称为 限定 列,这是避免在尝试 join
.
如果列名不明确,请限定它们,例如
select table_A.col_1, table_A.col_2, table_A.col_3
from table_A
join table_B on table_A.col_1 = table_B.col_2
或者为简洁起见,您可以为表分配一个别名:
select a.col_1, a.col_2, a.col_3
from table_A a
join table_B b on a.col_1 = b.col_2