防止 WHERE 在同一行匹配

问题描述 投票:0回答:2

我有一个包含两个表的数据库,

ships
officers
。一个
ship
有多个
officers
。要搜索具有特定
ship
officer
,我有这样的查询:

SELECT a.id
FROM ships AS a 
LEFT JOIN bridge_officers AS aBoff ON a.id = aBoff.ship_id  
WHERE aBoff.profession = :aprofession
GROUP BY a.id

这将导致所有具有

ships
officer
具有
:aprofession
。相同的
JOIN
/
WHERE
被重复过滤超过一个
officer
.

例如:

SELECT a.id
FROM ships AS a 
LEFT JOIN bridge_officers AS aBoff ON a.id = aBoff.ship_id
LEFT JOIN bridge_officers AS bBoff ON a.id = bBoff.ship_id
WHERE  aBoff.profession = :aprofession AND  bBoff.rank = :brank
GROUP BY a.id

这将导致所有

ships
具有
:aprofession
:brank
officers
。我想要的行为是只返回符合这些条件的两个不同的
officers
。如果一个
officer
同时具有
:aproffesion
:brank
,它将返回那艘船。如果每个
WHERE
条件只匹配一个连接,我更愿意。

有没有办法做到这一点?谢谢!

mysql mysqli
2个回答
0
投票

为第二个 JOIN 添加另一个条件,它是不同的官员。

SELECT DISTINCT a.id
FROM ships AS a 
LEFT JOIN bridge_officers AS aBoff ON a.id = aBoff.ship_id
LEFT JOIN bridge_officers AS bBoff ON a.id = bBoff.ship_id AND aBoff.id != bBoff.id
WHERE  aBoff.profession = :aprofession AND  bBoff.rank = :brank

0
投票

在连接条件中添加条件以防止同行匹配:

LEFT JOIN bridge_officers AS bBoff ON a.id = bBoff.ship_id
    AND aBoff.id < bBoff.id

选择

<
而不是
!=
将中间结果集减半;只产生任何两名军官的独特组合。

此外,

where
条款中似乎存在错误 - 您的问题说明 where
检查官员是否作为某种职业和 
other

官员是否有一定的等级 - 似乎条件应该应用于同一个连接表
WHERE aBoff.profession = :aprofession
AND bBoff.rank = :brank

aBoff

您的查询还有另一个微妙的问题:通过将 
WHERE aBoff.profession = :aprofession AND aBoff.rank = :brank -- aBoff.rank, not bBoff.rank

子句应用于外部联接表,您将它们转换为
inner
联接,因为联接行必须存在(并被联接到)才能使

where

 子句是真的,所以 
where 关键字在这里没有意义,为了清楚起见应该删除:
LEFT

© www.soinside.com 2019 - 2024. All rights reserved.