Laravel 7 MySQL联合查询

问题描述

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

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

然后我要再次查询用户表并获取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);

解决方法

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

对于您的语法错误,为()$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();

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...