首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Laravel 7 mysql联合查询

Laravel 7 mysql联合查询
EN

Stack Overflow用户
提问于 2020-09-04 03:22:01
回答 1查看 195关注 0票数 0

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

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

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

不确定连接是否更好,如果是的话,如何编写该查询,或者UNION是否工作。

我的问题是,下面的查询给出了一个错误,即:

代码语言:javascript
复制
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)))

这里是我的查询

代码语言:javascript
复制
    $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);
EN

回答 1

Stack Overflow用户

发布于 2020-09-04 11:55:48

从逻辑上说,您的查询看起来不太好,因为您有来自第一次查询$firstdata的2列和来自其他查询的单列。工会会员应该有同样的号码。列。

对于语法错误,有额外的()$firstdata$seconddata添加

代码语言:javascript
复制
(select query 3)
union
( <-----
    (select query 2)
    union
    (select query 1)
) <-----

以上应是

代码语言:javascript
复制
(select query 3)
union
(select query 2)
union
(select query 1)

我想您可以使用带有最终查询的多个union()子句来消除语法错误。

代码语言:javascript
复制
$thirddata = DB::table('users')
    ->select('users.name')
    ->where('client_profiles.account_rep', '=', 'users.id')
    ->union($seconddata)
    ->union($firstdata)
    ->get();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63734351

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档