我正在尝试使用以下 sql 查询我的 mysql 数据库:
$sql = "
SELECT
t1.Discipline,
t4disc.Color,
t4disc.Naam,
t1.Date_Posted,
t2ploeg.Naam PloegId,
t1.Cat,
t1.Tekst,
t3user.Naam PosterId,
t3user.Voornaam
FROM Log_Logboek_".$log." t1
JOIN Log_Ploegen_".$log." t2ploeg ON t1.PloegId = t2ploeg.ID
JOIN Log_Users t3user ON t1.PosterId = t3user.ID
JOIN Log_Disciplines t4disc ON t1.Discipline = t4disc.ID
". $where ."
AND t1.Discipline in ($vis_ids)
ORDER by Date_Posted asc;
";
该查询确实有效并给出了结果。连接的唯一问题是,如果连接的表之一不包含匹配的 Id,则该行将从结果中完全跳过。 例如,假设从 Log_Users 表中删除了一个用户,那么在此查询中将跳过具有该 ID 的所有记录,因为 t1.PosterId 没有匹配的用户。
有没有一种方法可以连接这些表,以便我可以在一个查询中完成它,并且仍然获得结果中的所有行?如果是这样,我可以以某种方式替换丢失的 id 吗?
如有任何帮助,我们将不胜感激。
最佳答案
我认为这是您想要的查询:
SELECT t1.Discipline, t4disc.Color, t4disc.Naam, t1.Date_Posted, t2ploeg.Naam PloegId,
t1.Cat, t1.Tekst, t3user.Naam PosterId, t3user.Voornaam
FROM Log_Logboek_".$log." t1 LEFT JOIN
Log_Ploegen_".$log." t2ploeg
ON t1.PloegId = t2ploeg.ID LEFT JOIN
Log_Users t3user
ON t1.PosterId = t3user.ID LEFT JOIN
Log_Disciplines t4disc
ON t1.Discipline = t4disc.ID
". $where ."t1.Discipline in ($vis_ids)
ORDER by Date_Posted asc;
where
子句中的条件位于第一个表上,因此它将相应地过滤行。如果没有与条件匹配的内容,则所有内容都可能被过滤掉。
如果将 where
条件移至 on
子句,则左外连接会发生奇怪的事情。 on
条件失败,但该行仍保留在结果集中——这就是左外连接的工作原理。
关于php - 在sql中使用连接 - 没有得到所有想要的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23980418/