获取关系 (one-to-many) 不存在于同一 table 中的计数

Get count where relation (one-to-many) doesnt exists in same table

我正在尝试获取没有关系的记录数 (one-to-many),但问题是它在同一个 table 中,我不知道该怎么做。

| id | person_id    | name       | 
+----+--------------+------------|        
|  1 | NULL         | John Doe   |
+----+--------------+------------|    
|  2 | NULL         | Jane Doe   |  
+----+--------------+------------+ 
|  3 | 1            | Junior J.D.|  
+----+--------------+------------+
|  4 | 1            | Senior J.D.|  
+----+--------------+------------+

现在,例如,我想得到 count = 1,因为 Jane Doe 没有恋爱关系(没有 one-to-many)。

为了更好的解释,我需要(例如)"Single" 的人,因为 "John Doe" 有 child "Junior J.D.",所以他不算数。

我知道如何统计没有关系的人(使用 Laravel Raw)

 $query = DB::table('people')
                 ->select(DB::raw('count(*) as count'))
                 ->where('person_id', '=', NULL)
                 ->get();

现在我想我会使用 Exists 但我不确定如何实现它(或者我可能错了)。

您可以使用 whereNull 方法来仅获取具有 NULL 值的列的行。

所以,

编辑:经过您的编辑,我想我理解了问题。

此 SQL 查询应该适合您:

SELECT COUNT(*) as count
FROM people
WHERE person_id IS NULL
    AND id NOT IN (
         SELECT person_id 
         FROM people 
         WHERE person_id IS NOT NULL
    );

如果我们将其翻译成 Laravel:

$query = DB::table('people')
             ->whereNull('person_id')
             ->whereIn('id', function($query) {
                 $query->select('person_id')
                       ->from('people')
                       ->whereNotNull('person_id');
             }, 'and', TRUE)
             ->count();

whereInSub 的第三个参数用于布尔逻辑组合查询。第四个参数意味着我们想要 NOT IN.

这没有经过测试。所以请测试它,让我知道它是否有效。

我想这也不是最好的方法。如果可能的话,我建议更改您的数据库结构。

这样做

$query = DB::table('people')
        ->whereNull('person_id')
        ->groupBy('name')
        ->count();

尝试使用 whereNull 而不是 where('person_id', '=', NULL)。进一步将 name 列拆分为 firstnamelastname 列,然后您可以执行以下操作:

$query = DB::table('people')
    ->whereNull('person_id')
    ->groupBy('lastname')
    ->count();