mysql - 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);
解决方案
从逻辑上讲,您的查询看起来不太好,因为您有来自第一个查询的 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();
推荐阅读
- c# - 使用 Udi Dahan 事件示例在 ASP.NET Core 中注册事件处理程序
- laravel - 如何在刀片中显示组件?
- python-3.x - 拆分文本并根据文本创建新列
- javascript - 将 xml 字符串转换为实际 xml 并提取特定属性
- django-rest-framework - django Swagger 无法添加参数说明
- python - 定义仅在 ast.While 对象中使用的访问方法
- typescript - 为什么 tsc 报告 SomeType 没有索引签名?
- javascript - 以顺时针方向循环一组数字
- spring - 当 Spring Security 中的会话超时时,SavedRequestAwareAuthenticationSuccessHandler 无法按预期工作
- ffmpeg - mp4s 的 ffmpeg concat 在连接处跳转并暂停几秒钟