SQL查询在mySQL中工作,在Laravel查询构建器中中断

oxf4rvwz  于 2023-04-28  发布在  Mysql
关注(0)|答案(2)|浏览(135)

我有一个SQL SELECT查询,它可以在mySQL中工作,既可以从PHPmyadmin也可以从控制台工作。然而,当它被转换为Laravel查询构建器时,它出现了以下错误消息:

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #3 of SELECT list is not
in GROUP BY clause and contains nonaggregated column 'wcce_dev.client_contacts.family_name'
which is not functionally dependent on columns in GROUP BY clause; this is incompatible with 
sql_mode=only_full_group_by

以下是SQL SELECT查询:

SELECT `clients`.name, `clients`.address_1, `client_contacts`.family_name,
  `client_contacts`.given_name, `client_contacts`.office_country,
  `client_contacts`.office_city, `client_contacts`.office_number, `client_contacts`.position, `contact_titles`.description
FROM `clients`
INNER JOIN `client_contacts`
ON `clients`.entry = `client_contacts`.client
INNER JOIN `contact_titles`
ON `client_contacts`.title = `contact_titles`.code
GROUP BY `clients`.entry
ORDER BY `clients`.entry ASC;

下面是Laravel查询生成器语句:

DB::table('clients')
->select('clients.name', 'clients.address_1', 'client_contacts.family_name',
  'client_contacts.given_name', 'client_contacts.office_country', 
  'client_contacts.office_city', 'client_contacts.office_number', 
  'client_contacts.position', 'contact_titles.description')
->join('client_contacts','clients.entry','=','client_contacts.client')
->join('contact_titles','client_contacts.title','=','contact_titles.code')
->groupBy('clients.entry')
->orderBy('clients.entry','asc')
->get();

很奇怪任何帮助都非常感谢。

oaxa6hgo

oaxa6hgo1#

问题是相关表client_contacts可以有多行对应于clients表中的一行。即使它在现实中不会发生,数据库也不知道这一点,并抛出一个错误。
你有两个选择
1.关闭sql_mode=only_full_group_by,以便它可以随机选取一行并显示
1.在每个聚合列之前加上MAX(),以便它只获取其中一个。
结果查询如下所示:

SELECT `clients`.name, `clients`.address_1, 
  MAX(`client_contacts`.family_name),
  MAX(`client_contacts`.given_name), 
  MAX(`client_contacts`.office_country),
  MAX(`client_contacts`.office_city), 
  MAX(`client_contacts`.office_number),   
  MAX(`client_contacts`.position), 
  MAX(`contact_titles`.description)
FROM `clients`
INNER JOIN `client_contacts`
ON `clients`.entry = `client_contacts`.client
INNER JOIN `contact_titles`
ON `client_contacts`.title = `contact_titles`.code
GROUP BY `clients`.entry
ORDER BY `clients`.entry ASC;
ergxz8rk

ergxz8rk2#

在mysql中试试这个命令,phpmyadmin然后试试
SET GLOBAL sql_mode=(SELECT CONCAT(@@sql_mode,',ONLY_FULL_GROUP_BY'));
如果使用group by,则group by列必须出现在选择查询“客户端”中。入口'“

DB::table('clients')
->select('clients.name', 'clients.address_1', 'client_contacts.family_name',
  'client_contacts.given_name', 'client_contacts.office_country', 
  'client_contacts.office_city', 'client_contacts.office_number', 
  'client_contacts.position', 'contact_titles.description', 'clients.entry')
->join('client_contacts','clients.entry','=','client_contacts.client')
->join('contact_titles','client_contacts.title','=','contact_titles.code')
->groupBy('clients.entry')
->orderBy('clients.entry','asc')
->get();

相关问题