【发布时间】:2018-08-25 23:17:49
【问题描述】:
SQL 查询不是我的强项之一,我遇到了一个我能够解决但希望改进并提高效率的问题。我在这些示例中使用了 Laravel 的查询生成器,但如果必须,我不介意使用原始请求。
目前我正在做如下两个查询并在之后合并它们。
$acc_id = 10;
$locat_id= 3;
//First get all sites with account id
$allSites = collect(DB::table('sites')->where('acc_id', $acc_id)->get()):
//Next get only sites with account id and connections with current location id
$connectedSites = collect(
DB::table('sites')
->select('sites.id','name','active','url')
->join('connections as conn','sites.id','=','conn.site_id')
->where('acc_id',$acc_id)
->where('conn.locat_id',$locat_id)
->get()
);
//Merge the collections and drop first row with duplicate site_id
$sites = $allSites->merge($connectedSites)->keyBy('id');
return $sites;
所以这给了我想要的结果。例如。与帐户 ID 关联的所有站点,以及与帐户 ID 和位置 ID 关联的站点的连接数据。 但是,如果可能的话,我想学习如何在一个查询中执行此操作。
【问题讨论】:
-
每个站点是否至少有一个连接?
-
没有,有些网站没有连接。它们(站点)在创建帐户时默认添加。连接由用户稍后进行。
-
也许问题的一部分可能是我对表关系的工作方式设计不佳。在这一点上,它可以按照我的需要完美运行,但我喜欢尽可能地改进。