Illegal mix of collations for operation 'UNION' Nodejs Mysql - 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.

Related

Add a foregin key to a different table

I'm trying to add username from my st_accounts column into my table results using mySQL.
st_accounts table
`id` int(11) NOT NULL, //Primary Key
`firstname` varchar(50) NOT NULL,
`lastname` varchar(50) NOT NULL,
`username` varchar(50) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(100) NOT NULL,
`img` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
results table
`score_ID` int(11) NOT NULL, //Primary key
`score` int(20) NOT NULL,
`date` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I think you want:
create table accounts (
account_id int auto_increment primary key,
. . .
);
create table results (
result_id int auto_increment primary key,
account_id int not null
score int NOT NULL,
score_date date NOT NULL,
constraint fk_results_accounts foreig key (accounts_id) references accounts(account_id)
) ;
Notes:
Declare the primary key explicitly, not in a comment.
My convention is to name the primary key after the name of the table (in singular) with _id after it.
The foreign key has the same name as the primary key -- self documenting.
I made the integer primary keys auto_increment, so the database can assign unique values.

MySQL JOIN Posts - Tags is taking too long

I'm facing some performance issues on MySQL JOIN statement. It's basically a posts-tags relationship with many rows: about 100000 posts and 20000 tags.
Unfortunately the query takes too long so that's what I'm asking for your help.
In a very basic query I need to get specific posts columns plus concatenated tags for each post. In fact the real query is more complex but I could start from here.
This is my query:
SELECT
SQL_CALC_FOUND_ROWS null as rows,
posts.id,
posts.title
GROUP_CONCAT(tags.desc SEPARATOR ", ") as ptags
FROM posts
JOIN posts_tags ON posts_tags.id_post = posts.id
JOIN tags ON tags.id = posts_tags.id_tag
GROUP BY posts.id
ORDER BY posts.id DESC
LIMIT 0,20
These are my keys definition
--- POSTS Table ----
PRIMARY KEY (`id`)
--- POSTS_TAGS Table ----
PRIMARY KEY (`id`),
KEY `id_post` (`id_post`),
KEY `id_tag` (`id_tag`)
--- TAGS Table ----
PRIMARY KEY (`id`)
This is my very first post, so I'm sorry if I've missed something. Any help will be appreciated.
**** EDIT ****
Added real Tables and Queries. Note that Posts is now named Noticias and Posts_tags is now named Tags_Noticias . Added MySQL Explain from PHPMyAdmin and JetProfiler.
CREATE TABLE IF NOT EXISTS `noticias` (
`id` int(9) NOT NULL AUTO_INCREMENT,
`volanta` varchar(150) DEFAULT NULL,
`titulo` varchar(250) NOT NULL,
`texto` text NOT NULL,
`fecha` datetime NOT NULL,
`fecha_modificado` datetime NOT NULL,
`id_autor` int(2) NOT NULL,
`id_seccion` int(2) NOT NULL,
`id_posicion` int(1) NOT NULL,
`publicado` int(1) NOT NULL DEFAULT '1',
`clave_primaria` varchar(30) DEFAULT NULL,
`url` varchar(500) NOT NULL,
`meta_titulo` varchar(100) NOT NULL,
`meta_descripcion` varchar(200) NOT NULL,
`redirect` int(1) NOT NULL,
`estado_seo` varchar(10) NOT NULL DEFAULT 'danger',
`geo_data` varchar(50) DEFAULT NULL,
`media_principal` varchar(500) NOT NULL,
PRIMARY KEY (`id`),
KEY `id_autor` (`id_autor`),
KEY `id_seccion` (`id_seccion`),
KEY `id_posicion` (`id_posicion`),
KEY `fecha` (`fecha`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=98560;
-
CREATE TABLE IF NOT EXISTS `tags` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`descripcion` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `descripcion` (`descripcion`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=21097 ;
-
CREATE TABLE IF NOT EXISTS `tags_noticias` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_tag` int(11) NOT NULL,
`id_noticia` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `id_noticia` (`id_noticia`),
KEY `id_tag` (`id_tag`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=284979 ;
-
SELECT
SQL_CALC_FOUND_ROWS null as rows,
noticias.id,
noticias.titulo,
noticias.fecha,
noticias.url,
noticias.publicado,
noticias.estado_seo,
GROUP_CONCAT(tags.descripcion SEPARATOR ", ") as ntags
FROM noticias
JOIN tags_noticias ON tags_noticias.id_noticia = noticias.id
JOIN tags ON tags.id = tags_noticias.id_tag
GROUP BY noticias.id
ORDER BY noticias.id DESC
LIMIT 0,20
MySQL explain
JetProfiler Explain

MySQL filtering result from a foreign key that doesn't have contents

i have two tables:
CREATE TABLE IF NOT EXISTS `test_category` (
`_id` int(11) NOT NULL AUTO_INCREMENT,
`score_type` varchar(50) NOT NULL,
`sub_code` int(11) NOT NULL,
`duration` varchar(10) NOT NULL,
`status` int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (`_id`),
KEY `sub_code` (`sub_code`)
)
CREATE TABLE IF NOT EXISTS `questions` (
`_id` int(11) NOT NULL AUTO_INCREMENT,
`question` varchar(255) NOT NULL,
`correct_ans` varchar(255) NOT NULL,
`incorrect1` varchar(255) NOT NULL,
`incorrect2` varchar(255) NOT NULL,
`incorrect3` varchar(255) NOT NULL,
`test_cat` int(11) NOT NULL,
`image_location` varchar(50) NOT NULL,
PRIMARY KEY (`_id`),
KEY `test_cat` (`test_cat`)
)
ALTER TABLE `questions`
ADD CONSTRAINT `questions_ibfk_1` FOREIGN KEY (`test_cat`) REFERENCES `test_category` (`_id`);
so basically these two tables are related. questions table is related to test_category table through the foreign key test_cat from the table questions referenced to the _id of test_category. what i wan't to display is those entry from test_category that have a entries related to it from the questions table. if an entry from test_category doesn't have anything referenced to it from the questions table then it shouldn't be displayed.
select distinct test_category._id, test_category.score_type
from test_category join questions
where ??
that's the sql i have tried but i don't know how to filter it with where...
select distinct test_category._id, test_category.score_type from test_category
join questions
on 'questions.test_cat' = 'test_category._id'
select distinct test_category._id, test_category.score_type from test_category
join questions
on questions.test_cat = test_category._id
kudos to Nisha and Abhik Chakraborty

Optimize sql query to speed up a search which currently takes around 85 seconds

I have a database with the records near about 2.7 milion . I need to fetch records from that for that i am using the below query
for result
SELECT r3.original_image_title,r3.uuid,r3.original_image_URL FROM `image_attributes` AS r1 INNER JOIN `filenames` as r3 WHERE r1.`uuid` = r3.`uuid` and r3.`status` = 1 and r1.status=1 and (r1.`attribute_name` like "Quvenzhané Wallis%" or r3.original_image_URL like "Quvenzhané Wallis%") group by r3.`uuid` limit 0,20
for total count
SELECT count(DISTINCT(r1.`uuid`)) as count FROM `image_attributes` AS r1 INNER JOIN `filenames` as r3 WHERE r1.`uuid` = r3.`uuid` and r3.`status` = 1 and r1.status=1 and (r1.`attribute_name` like "Quvenzhané Wallis%" or r3.original_image_URL like "Quvenzhané Wallis%")
table structures are as below
CREATE TABLE IF NOT EXISTS `image_attributes` (
`index` int(11) NOT NULL AUTO_INCREMENT,
`attribute_name` text NOT NULL,
`attribute_type` varchar(255) NOT NULL,
`uuid` varchar(255) NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`index`),
KEY `attribute_type` (`attribute_type`),
KEY `uuid` (`uuid`),
KEY `status` (`status`),
KEY `attribute_name` (`attribute_name`(50))
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2730431 ;
CREATE TABLE IF NOT EXISTS `filenames` (
`index` int(11) NOT NULL AUTO_INCREMENT,
`original_image_title` text NOT NULL,
`original_image_URL` text NOT NULL,
`uuid` varchar(255) NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`index`),
KEY `uuid` (`uuid`),
KEY `original_image_URL` (`original_image_URL`(50))
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=591967 ;
please suggest me how can i optimize the queries to make the search result faster
I would recommend to you a book called 'High Performance MySql'. There is a section called Optimize databases and queries, or something like that.

Error creating table: You have an error in your SQL syntax near 'order( order_id INT UNSIGNED NOT NULL AUTO_INCREMENT, user_id ' at line 1 [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
I am trying to create 2 tables in the same MySQL database with a PHP-script:
table 'user' with primary key 'user_id' and table 'order' with primary key 'order_id' and foreign key 'user_id' from the 'user' table (1 to many relationship).
Table user creates successfully without problems:
$sql="CREATE TABLE user(
user_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
type ENUM('member','admin') NOT NULL,
username VARCHAR(30) NOT NULL,
email VARCHAR(80) NOT NULL,
pass VARBINARY(32) NOT NULL,
first_name VARCHAR(40) NOT NULL,
last_name VARCHAR(40) NOT NULL,
date_expires DATE NOT NULL,
date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
date_modified TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (user_id),
UNIQUE (username),
UNIQUE (email)
)ENGINE=InnoDB DEFAULT CHARSET=utf8";
However, I am not able to create table order:
$sql="CREATE TABLE order(
order_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id INT UNSIGNED NOT NULL,
transaction_id VARCHAR(19) NOT NULL,
payment_status VARCHAR(15) NOT NULL,
payment_amount DECIMAL(6,2) UNSIGNED NOT NULL,
payment_date_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (order_id),
FOREIGN KEY (user_id) REFERENCES user (user_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8";
I get the following error:
Error creating table: 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 'order( order_id INT UNSIGNED NOT NULL AUTO_INCREMENT, user_id ' at line 1
Already checked the syntax and cannot find the mistake. Could you please advise what went wrong? Thanks a lot.
You need to escape reserved words like order with backticks
CREATE TABLE `order` ( ...
or better use another name instead.
order is keyword used by mysql like (select from tbl_name order by id ASC) so for escaping from using keywords you have to use quotes `` to avoid my sql error
so your query should by
$sql="CREATE TABLE `order` (
order_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id INT UNSIGNED NOT NULL,
transaction_id VARCHAR(19) NOT NULL,
payment_status VARCHAR(15) NOT NULL,
payment_amount DECIMAL(6,2) UNSIGNED NOT NULL,
payment_date_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (order_id),
FOREIGN KEY (user_id) REFERENCES user (user_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8";
enjoy :D