Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在sql中使用连接-无法获得所有想要的结果_Php_Mysql_Sql_Join - Fatal编程技术网

Php 在sql中使用连接-无法获得所有想要的结果

Php 在sql中使用连接-无法获得所有想要的结果,php,mysql,sql,join,Php,Mysql,Sql,Join,我正在尝试使用以下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

我正在尝试使用以下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
条件失败,但行仍保留在结果集中——这就是左外部联接的工作方式。

左联接替换您的
联接
s。这是实现您所需的SQL构造。这是idd—使用“null”填充未知id来获取所有结果的方法。问题是现在我的where语句不再工作了:
$where='和t1.Date\u Posted>='。$timestamp和…
开始的,这在我以前的sql中是正常连接的。使用左连接,我将
替换为
WHERE
,然后它就工作了!谢谢你的帮助!