首页 > 解决方案 > Laravel 7 mysql联合查询

问题描述

我正在构建一个 Laravel 7 应用程序并尝试使用 UNION 创建一个复杂的查询,我认为这是我想要做的。

这是我想要做的:我想查询列 roleid = 0 的 users 表,然后我想查询 userid 列等于 users 表中 id 列的值的 client_profiles 表。

然后我想(再次)查询 users 表并获取 name 列的值,其中 id 列等于 client_profiles 表列 account_rep_id 的值

不确定连接是否会更好,如果是这样,如何编写该查询或 UNION 是否可以工作。

我的问题是下面的查询给了我一个错误,上面写着:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL 
syntax; check the manual that corresponds to your MySQL server version for the right 
syntax to use near 'union (select `users`.`name`, `users`.`system_account_status` from 
`users` where' at line 1 (SQL: (select `users`.`name` from `users` where 
`client_profiles`.`account_rep` = users.id) union ((select `client_profiles`.`account_rep` 
from `client_profiles` where `client_profiles`.`userid` = users.id) union (select 
`users`.`name`, `users`.`system_account_status` from `users` where `roleid` = 0)))

这是我的查询

    $firstdata = DB::table('users')
        ->select('users.name','users.system_account_status')
        ->where('roleid', '=', 0);

    $seconddata = DB::table('client_profiles')
        ->select('client_profiles.account_rep')
        ->where('client_profiles.userid', '=', 'users.id')
        ->union($firstdata);
    
    $thirddata = DB::table('users')
        ->select('users.name')
        ->where('client_profiles.account_rep', '=', 'users.id')
        ->union($seconddata)
        ->get();
    print_r($thirddata);

标签: mysqljoinunionslaravel-7

解决方案


从逻辑上讲,您的查询看起来不太好,因为您有来自第一个查询的 2 列$firstdata和来自其他查询的单列。联合查询应该有相同的编号。列。

对于您的语法错误,为and()添加了额外的 s$firstdata$seconddata

(select query 3)
union
( <-----
    (select query 2)
    union
    (select query 1)
) <-----

上面应该是

(select query 3)
union
(select query 2)
union
(select query 1)

union()我想你可以通过在最终查询中使用多个子句来消除语法错误

$thirddata = DB::table('users')
    ->select('users.name')
    ->where('client_profiles.account_rep', '=', 'users.id')
    ->union($seconddata)
    ->union($firstdata)
    ->get();

推荐阅读