简体   繁体   English

从 mysql JOIN 获取所有结果,即使没有连接匹配

[英]Get all results from mysql JOIN, even if no join matches

I am doing a JOIN operation between a table and itself.我正在表和它本身之间进行 JOIN 操作。 The table schema is something like:表架构类似于:

| id | name | parent |
|  0 | .... |   ...  |
|  1 | .... |   ...  |
|  2 | .... |   ...  |

The query looks like:查询如下所示:

$qMarks = str_repeat('?,', count($arr) - 1) . '?';
$stmt = $db->prepare("SELECT t1.id AS t1id, t1.name AS t1name, t2.name AS t2name 
                            FROM cats t1 
                            JOIN cats t2 ON t1.parent = t2.id
                            WHERE t1.name IN ($qMarks)");
$stmt->execute($arr);
$result = $stmt->fetchAll();

So, I'm passing in an array of names $arr , and I am getting back the rows where there is a matching name to one of the items in the parameter array.因此,我传入了一个名称数组$arr ,并且我返回了与参数数组中的一个项目具有匹配名称的行。 This works fine, so long as there is also a matching id somewhere for parent .这工作正常,只要在某处还有一个匹配的idparent

But, sometimes the value for parent will be blank (empty cell).但是,有时parent的值将为空白(空单元格)。 I still want to get those results, as long as the t1.name IN ($qMarks) condition is met.我仍然想得到那些结果,只要满足t1.name IN ($qMarks)条件。

How do I return the values, even if the t1.parent value in the table is blank?即使表中的t1.parent值为空,我如何返回值?

Use a left join .使用左连接

$stmt = $db->prepare("SELECT t1.id AS t1id, t1.name AS t1name, t2.name AS t2name 
                        FROM cats t1 
                        LEFT JOIN cats t2 ON t1.parent = t2.id
                        WHERE t1.name IN ($qMarks)");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM