我正在构建一个Laravel 7应用程序,并试图创建一个复杂的查询使用UNION,我认为这是我想要做的。
这里是我想要做的:我想在列roleid =0的地方查询users表,然后从users表中查询userid列等于id列的值的client_profiles表。
然后,我想查询users表(再次),并从client_profiles表列account_rep_id中获得id列等于值的name列的值。
不确定连接是否更好,如果是的话,如何编写该查询,或者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);发布于 2020-09-04 11:55:48
从逻辑上说,您的查询看起来不太好,因为您有来自第一次查询$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();https://stackoverflow.com/questions/63734351
复制相似问题