MySql 具有多个正确出现之一的联合
MySql Joint with having one of multiple right occurence
我有 2 table(A 和 B)。 table A 上的每一行在 table B 上最多有 3 个对应关系。Table B 有一个状态字段,可以是 "x" "y" 或 "null".
我想从 table A 中获取所有行,其中 table B 中没有匹配行具有 "X" 状态(见下图)。所以基本上我想要 ID 为 2 和 3 的行。
注意,我的 from 语句必须在 Table A.
到目前为止,我尝试了以下但没有成功:
select *
from table A
left join table B on a.Id = b.ref
where status = 'Y'
or status is null;
select *
from table A
right join table B on a.Id = b.ref
where status = 'Y'
or status is null;
问题是对于 table A 中的每一行,我在 table B 中有一行满足 where 条件,所以我返回了所有 3 行,而不是只有绿色的一行。我需要做一些事情,比如“让所有匹配的行来自 table B != "X"
Select A.*
from A
where A.Id not in (select ref
from B
where B.ref = A.Id
and B.Status = 'X')
您的想法是尝试将 table A 中的行与 table B 中的任何人进行匹配,但仅匹配 x
中的行。
如果你做不到,你会得到 NULL
,这些就是你想要的行。
SELECT A.*
FROM TableA as A
LEFT JOIN TableB as B
ON A.id = B.Ref
AND B.status = 'x'
WHERE B.status is null
我有 2 table(A 和 B)。 table A 上的每一行在 table B 上最多有 3 个对应关系。Table B 有一个状态字段,可以是 "x" "y" 或 "null".
我想从 table A 中获取所有行,其中 table B 中没有匹配行具有 "X" 状态(见下图)。所以基本上我想要 ID 为 2 和 3 的行。
注意,我的 from 语句必须在 Table A.
到目前为止,我尝试了以下但没有成功:
select *
from table A
left join table B on a.Id = b.ref
where status = 'Y'
or status is null;
select *
from table A
right join table B on a.Id = b.ref
where status = 'Y'
or status is null;
问题是对于 table A 中的每一行,我在 table B 中有一行满足 where 条件,所以我返回了所有 3 行,而不是只有绿色的一行。我需要做一些事情,比如“让所有匹配的行来自 table B != "X"
Select A.*
from A
where A.Id not in (select ref
from B
where B.ref = A.Id
and B.Status = 'X')
您的想法是尝试将 table A 中的行与 table B 中的任何人进行匹配,但仅匹配 x
中的行。
如果你做不到,你会得到 NULL
,这些就是你想要的行。
SELECT A.*
FROM TableA as A
LEFT JOIN TableB as B
ON A.id = B.Ref
AND B.status = 'x'
WHERE B.status is null