简体   繁体   English

选择存在子关系(子查询)作为1/0列

[英]Selecting existence of child relationship (subquery) as 1/0 column

I am trying to get the result of a subquery as a column that is 1 or 0 based on its relationship. 我正在尝试根据其关系将子查询的结果作为1或0的列。

This is a heavy report as well, so I want to avoid extra queries after the initial query. 这也是一份繁重的报告,因此我想避免在初始查询之后进行额外的查询。

DB::raw('EXISTS(
   SELECT 1 
   FROM issues 
   WHERE time.id = issues.parent_id 
      AND parent_type = \'' . TimeRecord::class . '\' 
      AND deleted_at IS NULL
   ) AS flagged')

The rest of the query works, and even with this still works (just always is 0 even for rows that should be 1. 查询的其余部分仍然有效,即使这样也仍然有效(即使对于应为1的行,始终为0。

I have not found any instance of EXISTS used like this, but I have not found any alternative used as a column. 我还没有找到像这样使用的EXISTS任何实例,但是我还没有找到任何用作列的替代方法。

Have you tried COUNT ? 您尝试过COUNT吗?

SELECT COUNT(*)
FROM issues 
WHERE time.id = issues.parent_id 
   AND parent_type = \'' . TimeRecord::class . '\' 
   AND deleted_at IS NULL

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

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