SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB - sql

I'm getting this error in Laravel 8
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '*)
This is how I'm trying to do the query
$totalCitasGenero = DB::table('citas')->selectRaw('idEspecialidad, genero, count (*) as totalCitas')->join('personas', 'personas.id', '=', 'citas.idPersonaP')->groupBy('idEspecialidad','genero')->get();
This is how my tables looks like
CREATE TABLE `personas` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nombre` varchar(50) NOT NULL,
`apellido` varchar(50) NOT NULL,
`cedula` varchar(10) NOT NULL,
`email` varchar(40) DEFAULT NULL,
`telefono` varchar(13) DEFAULT NULL,
`direccion` varchar(100) NOT NULL,
`ciudadResi` varchar(50) NOT NULL,
`fechaNacimiento` date NOT NULL,
`genero` varchar(100) NOT NULL,
`estado` binary(1) NOT NULL,
`idTipoPersona` int(11) NOT NULL,
`idPersona` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `personas_FK` (`idTipoPersona`),
KEY `personas_FK_1` (`idPersona`),
CONSTRAINT `personas_FK` FOREIGN KEY (`idTipoPersona`) REFERENCES `tipo_personas` (`id`),
CONSTRAINT `personas_FK_1` FOREIGN KEY (`idPersona`) REFERENCES `personas` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=73 DEFAULT CHARSET=utf8mb4
CREATE TABLE `citas` (
`idPersonaD` int(11) NOT NULL,
`idPersonaP` int(11) NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`fecha` date NOT NULL,
`hora` time NOT NULL,
`idEspecialidad` int(11) NOT NULL,
`estado` int(11) NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
KEY `citas_FK` (`idPersonaD`),
KEY `citas_FK_1` (`idPersonaP`),
KEY `citas_FK_2` (`idEspecialidad`),
CONSTRAINT `citas_FK` FOREIGN KEY (`idPersonaD`) REFERENCES `personas` (`id`),
CONSTRAINT `citas_FK_1` FOREIGN KEY (`idPersonaP`) REFERENCES `personas` (`id`),
CONSTRAINT `citas_FK_2` FOREIGN KEY (`idEspecialidad`) REFERENCES `especialidades` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=88 DEFAULT CHARSET=utf8mb4
on DBeaver the query works fine and this is how it looks like
select idEspecialidad, genero, count (*) as totalCitas
from citas as c join personas
where c.idPersonaP = personas.id
group by genero, idEspecialidad ;
The results I'm expecting are the ones in the picture below.
What is wrong translating the query into Laravel?
if I do a dd of the variable after I switch the ->get() as toSql() ->as suggested I get this result
"select idEspecialidad, genero, count (*) as totalCitas from `citas` inner join `personas` on `personas`.`id` = `citas`.`idPersonaP` group by `idEspecialidad`, `genero`
I have even tried coppying the query into DBeaver again and it works fine, its just in Laravel that isnt working not sure why.
The query looks fine so I have no idea why it doesn't work in this case.

Try removing the white space that you have in count (*)
$totalCitasGenero = DB::table('citas')->selectRaw('idEspecialidad, genero, count(*) as totalCitas')->join('personas', 'personas.id', '=', 'citas.idPersonaP')->groupBy('idEspecialidad','genero')->get();

Related

Mysql - Error code 1054 Unknown cloumn 'players.p_name' in 'where clause'

Hello,
first of all I want you to show my table I have:
CREATE TABLE `channels` (
`channel_id` int(11) NOT NULL AUTO_INCREMENT,
`channel_name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`channel_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
CREATE TABLE `gamepoints` (
`gp_id` int(11) NOT NULL AUTO_INCREMENT,
`gamble` int(11) DEFAULT NULL,
`roulette` int(11) DEFAULT NULL,
`blackjack` int(11) DEFAULT NULL,
`slots` int(11) DEFAULT NULL,
PRIMARY KEY (`gp_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
CREATE TABLE `player_channel` (
`pc_id` int(11) NOT NULL AUTO_INCREMENT,
`players_id` int(11) DEFAULT NULL,
`channel_id` int(11) DEFAULT NULL,
PRIMARY KEY (`pc_id`),
KEY `players_id_idx` (`players_id`),
KEY `channel_id_idx` (`channel_id`),
CONSTRAINT `channel_id` FOREIGN KEY (`channel_id`) REFERENCES `channels` (`channel_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `players_id` FOREIGN KEY (`players_id`) REFERENCES `players` (`players_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
CREATE TABLE `players` (
`players_id` int(11) NOT NULL AUTO_INCREMENT,
`p_name` varchar(45) DEFAULT NULL,
`p_right` varchar(45) DEFAULT NULL,
`gp_id` int(11) DEFAULT NULL,
PRIMARY KEY (`players_id`),
KEY `gp_id_idx` (`gp_id`),
CONSTRAINT `gp_id` FOREIGN KEY (`gp_id`) REFERENCES `gamepoints` (`gp_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
I wanted to this query:
UPDATE gamepoints SET gamble = 1
WHERE gamepoints.gp_id = players.gp_id
AND players.p_name = "test"
AND player_channel.players_id = players.players_id
AND player_channel.channel_id = channels.channel_id
AND channels.channel_name = "test";
But when I do this i get this Error:
Error Code: 1054. Unknown column 'players.p_name' in 'where clause'
I don't know what I am doing wrong, i tryed also after set to add from with all tables, but this works also not.
I would be really happy if someone can help me :)
Thanks in advance
You omitted the table names of all but gamepoints. I would recommend that you use explicit join update syntax, which makes it harder to have this sort of error:
UPDATE gamepoints t1
INNER JOIN players t2
ON t1.gp_id = t2.gp_id
INNER JOIN player_channel t3
ON t3.players_id = t2.players_id
INNER JOIN channels t4
ON t4.channel_id = t3.channel_id
SET t1.gamble = 1
WHERE t2.p_name = 'test' AND
t4.channel_name = 'test';
If you wanted to salvage your current query, then it would start off looking something like this:
UPDATE gamepoints, players, player_channel, channels
SET gamble = 1
WHERE -- a very large number of conditions
One reason implicit joins are frowned upon is that they mix normal restrictions on the result set with join conditions, all in the same WHERE clause. This doesn't happen with the query as I wrote it using explicit joins.

Error creating table with CREATE TABLE IF NOT EXISTS

I have an issue, I am getting the following error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use
near 'CREATE TABLE IF NOT EXISTS methods ( ID int(11) NOT NULL
AUTO_INCREMENT, ' at line 14
When I try and do this:
CREATE TABLE IF NOT EXISTS `methods` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`friendly` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=29 ;
I was wondering if anyone could help me, because in all honesty, I'm not too good with this stuff

SQLite database creating through script

There is the following script:
CREATE TABLE IF NOT EXISTS `location_cities` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`location_region_id` int(11) NOT NULL DEFAULT '0',
`location_district_id` int(11) DEFAULT NULL,
`location_country_id` int(11) NOT NULL DEFAULT '0',
`lon` float(11,8) NOT NULL DEFAULT '0.00000000',
`lat` float(11,8) NOT NULL DEFAULT '0.00000000',
`prefix` varchar(50) DEFAULT NULL,
`name` varchar(128) NOT NULL,
`size` int(3) NOT NULL DEFAULT '0' COMMENT 'Размер города',
`tz_name` varchar(128) DEFAULT NULL,
`timezone` varchar(100) NOT NULL DEFAULT '+00:00',
`timezone2` varchar(100) NOT NULL DEFAULT '+00:00',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=12393 ;
When I try to execute it using 'sqlite3 db/development.sqlite3 < alogist.sql' I got error 'Error: near line 27: near "AUTO_INCREMENT": syntax error' (27 - the line with "CREATE_TABLE ...". So, what's the trouble? How can I fix it? Thanks!
In sqlite, an autoincrement column is specified as
INTEGER PRIMARY KEY AUTOINCREMENT
Replace your int(11) NOT NULL AUTO_INCREMENT with that.
Further problems:
COMMENT is not supported. Remove COMMENT 'Размер города'
Remove PRIMARY KEY (ID) - the primary key has already been specified.
Remove the MySQL-specific ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=12393.
SQLite syntax:
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL

I get "a foreign key constraint fails" error when attempting to join two classes/tables

I have these classes, abbreviated for practical reasons:
class CV {
Date dateCreated
static hasMany=[proposals: Proposal]
}
class Proposal {
String name
Date date_started
static hasMany = [CVs: CV]
static belongsTo = CV
}
Grails creates tables for both these classes, and a third class named "cv_proposals" joining them. So far, so good. I have data in both the CV and the Proposal tables, they both have autoincremented "id" values. All good.
in Oracle MySQL Workbench, I try to manually add values to the joining table to get some dummy data to work with. I get an error message with this trace:
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails
(cvreg_utv.cv_proposals, CONSTRAINT FK17D946F55677A672 FOREIGN KEY (cv_id) REFERENCES cv (id))
I made sure both the tables had several lines of data in them, and that I could edit both of them separately.
After trying dropping and recreating the table, altering the classes back and forth, I'm kind of convinced that this operation somehow has to be done through a running Grails application. So I write this script in a controller and run it:
def g = CV.get(1)
Proposal proposal = g.addToProposals(new Proposal(
name: "SavingTest",
date_started: new Date())).save()
I still get the same error, though. Is this not the right way to define a proposal that is connected to a certain CV? Am I wrong in using a many-to-many connection here somehow?
Edit: adding the schema-create script for the joining table
delimiter $$
CREATE TABLE `cv_proposals` (
`proposal_id` bigint(20) NOT NULL,
`cv_id` bigint(20) NOT NULL,
PRIMARY KEY (`cv_id`,`proposal_id`),
KEY `FK17D946F55677A672` (`cv_id`),
KEY `FK17D946F5F7217832` (`proposal_id`),
CONSTRAINT `FK17D946F5F7217832` FOREIGN KEY (`proposal_id`) REFERENCES `proposal` (`id`),
CONSTRAINT `FK17D946F55677A672` FOREIGN KEY (`cv_id`) REFERENCES `cv` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
And the CV table:
CREATE TABLE `cv` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`version` bigint(20) NOT NULL,
`user_id` bigint(20) NOT NULL,
`version_name` varchar(255) DEFAULT NULL,
`date_created` datetime NOT NULL,
`last_updated` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `FKC734A9AB992` (`user_id`)
) ENGINE=MyISAM AUTO_INCREMENT=101 DEFAULT CHARSET=latin1$$
And the Proposal table:
CREATE TABLE `proposal` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`version` bigint(20) NOT NULL,
`date_ended` datetime NOT NULL,
`date_started` datetime NOT NULL,
`description` varchar(500) DEFAULT NULL,
`name` varchar(500) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1$$
This is the insert script I tried to run:
INSERT INTO `cvreg_utv`.`cv_proposals` (`proposal_id`, `cv_id`)
VALUES ('1', '1');
You crated the tables manually? It's interesting that cv table is using MyISAM engine and the others uses InnoDB.
I think you want to use InnoDB to all your tables, since this engine is transactional. In my test, I also was unable to create the cv_proposals table until I changed the cv creation:
CREATE TABLE cv (
id bigint(20) NOT NULL AUTO_INCREMENT,
version bigint(20) NOT NULL,
user_id bigint(20) NOT NULL,
version_name varchar(255) DEFAULT NULL,
date_created datetime NOT NULL,
last_updated datetime NOT NULL,
PRIMARY KEY (id),
KEY FKC734A9AB992 (user_id)
) ENGINE=InnoDB AUTO_INCREMENT=101
After that, the insert's worked smoothly.

How to insert into a table join other table using Activerecord in CodeIgniter?

I'm new to CodeIgniter and ORM, I hope you guys can help me with this.
The question table:
CREATE TABLE `question` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(128) NOT NULL DEFAULT '',
`content` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The answer table:
CREATE TABLE `answer` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`question_id` int(11) unsigned NOT NULL,
`content` text NOT NULL,
PRIMARY KEY (`id`),
KEY `question_id` (`question_id`),
CONSTRAINT `answer_ibfk_1` FOREIGN KEY (`question_id`) REFERENCES `question` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The equivalent SQL is:
INSERT INTO answer(content, question_id)
VALUES('Ironman', (select id
from question
where title ='favourite characters'
and content = 'Who is your favourite characters in Avanger?'));
Anyone can tell me how to achieve the same thing but using CodeIgniter Activerecord?
Don't do that, instead use the primary key (id) to insert directly into the base table.