我有一个有两列的表格。 第一表 UID、TID
另一个表有: 第二个表 UID、TID、DiffColumn
根据用户的 UID 和 DiffColumn,我需要查询用户的 UID 或 TID 是否在 FirstTable 中。 所以我需要加入 SecondTable 来获取 TID。
我尝试使用以下查询:
SELECT F.UID, F.TID FROM
FirstTable F
INNER JOIN
SecondTable S
ON F.UID = S.UID
UNION
SELECT F.UID, F.TID FROM
FirstTable F
INNER JOIN
SecondTable S ON F.TID = S.TID
WHERE S.DiffColumn= ''
AND S.UID = ''
但我认为我使这个查询过于复杂,并且 where 子句仅适用于第二个 select 语句。 我该如何最好地简化这个?
最佳答案
如果您希望确定 uid
上的匹配优先于 tid
上的匹配的优先级,请使用两个 left join
:
select f.uid, f.tid,
coalesce(su.?, st.?) as ? -- ? is a column you might want from secondtable
from firsttable f left join
secondtable su
on su.uid = f.uid left join
secondtable st
on st.tid = f.tid and
st.diffcolumn = '' and
st.uid = ''
where st.uid is not null or st.tid is not null;
或者,如果您不需要 secondtable
中的任何列,则可以只使用 exists
:
select f.*
where exists (select 1
from secondtable su
where su.uid = f.uid
) or
exists (select 1
from secondtable st
where st.tid = f.tid and
st.diffcolumn = '' and
st.uid = ''
);
尽管您可以在相关子句中使用 or
而不是两个 exists
,但我强烈建议不要这样做。 on
子句和相关子句中的 or
会成为性能 killer 。
关于mysql - 如何根据另一个表的字段进行查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56217994/