简体   繁体   中英

Illegal mix of collations for operation 'UNION' Nodejs Mysql

I´m trying to get all the posts that a user wrote using this sql:

'SELECT * FROM users WHERE username=? UNION ALL SELECT * FROM posts WHERE writer_name=?'

And i´m getting this error:

"Illegal mix of collations for operation 'UNION'"

tables

CREATE TABLE `claudioBlog`.`users` ( 
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT , 
  `username` VARCHAR(100) NOT NULL , 
  `email` VARCHAR(100) NOT NULL , 
  `age` VARCHAR(100),
  `discription` VARCHAR (255),
  `ocupation` VARCHAR (100),
  `profile_image` VARCHAR (100)
  `password` VARCHAR(255) NOT NULL , 
  PRIMARY KEY (`id`), UNIQUE (`email`)
  ) ENGINE = InnoDB
  
 CREATE TABLE posts (
  id int(11) NOT NULL AUTO_INCREMENT,
  title VARCHAR(50)  NOT NULL,
  category VARCHAR(50)  NOT NULL,
  body VARCHAR(2000)  NOT NULL,
  writer_id VARCHAR(50)  NOT NULL,
  writer_name VARCHAR(50)  NOT NULL,
  post_img VARCHAR(100),
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id)
 ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

What do i have to chage?

You want a join , not union . Presumably, writer_id is a foreign key reference to users(id)

SELECT p.*
FROM users u JOIN
     posts p
     ON p.writer_id = u.id
WHERE u.username = ? ;

Note: If write_id does indeed refer to users(id) , it is inappropriate to store write_name in posts , unless -- for some strange reason -- it can vary by post and is not the users real name.

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