简体   繁体   中英

MySQL m:n relation query through linking table returns null in production 8.0.13 but works locally 5.7.30

using following MySQL schema for relations:

table user with PK user_id
table blog with PK blog_id and FK user_id
table tag with PK tag_id
and linking table blog_tag with PK's and FK's as blog_id and tag_id (both ON DELETE CASCADE)

1) When developing locally on Ubuntu 18.04.1 with Node (12.16.2), Express (4.17.1) and mysql (2.18.2) the below query works no problem using mysql server 5.7.30 (client 14.14 if it matters):

"SELECT b.*
      , JSON_ARRAYAGG(JSON_OBJECT('id', t.tag_id, 'name', t.name, 'color', t.color)) AS tags 
   FROM blog b 
   JOIN blog_tag bt 
     ON bt.blog_id = b.blog_id 
   JOIN tag t 
     ON bt.tag_id = t.tag_id 
  WHERE b.blog_id = ?", [req.params.blog_id]

This is for the show page where it returns single blog together with array of tags as json objects. Works fine locally.

When running against production database (Clever Cloud MySQL add-on mysql server 8.0.13), the show query above returns result with every column null . Why??

2) When using exact query above but changing to LEFT JOIN instead of JOIN it works fine in production. Why is JOIN working in MySQL 5 but not MySQL 8 and what effect would LEFT JOIN have compared to JOIN to not break it?

Hope it's clear enough and thanks for help.

Your query is an aggregation query because JSON_ARRAYAGG() is an aggregation function.

You have no GROUP BY . Hence, all values in the SELECT should be arguments to aggregation functions. If there were a GROUP BY , the unaggregated columns would need to be compatible with the GROUP BY keys.

But, you have SELECT b.* -- so lots of columns are clearly not aggregated. This is a syntax error in SQL

The problem is that you have a malformed query that used to work with the default settings in MySQL because it allowed such malformed queries. Happily, that has been fixed in MySQL 8+, so the query does not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM