How to do a Select in an insert MySQL - mysql

My question is how do i do a select of one attribute in my table.
I have the following table->
CREATE TABLE `Group` (
`group_id` varchar(10) NOT NULL,
`user_id` varchar(10) NOT NULL,
`group_creator` varchar(20) NOT NULL,
`group_name` varchar(50) NOT NULL,
`date_created` datetime DEFAULT NULL,
CONSTRAINT UC_Group UNIQUE (group_id,group_code,group_name)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `Group`
ADD PRIMARY KEY (`group_id`),
ADD KEY (`user_id`);
I would like to insert the user_id from another table called User. However it is not working.
My insert is as follows->
INSERT INTO `Group` (`group_id`, `user_id`, `group_creator`, `group_name`, `date_created`)
SET `group_id`=UUID(), `user_id`=(SELECT user_id FROM User WHERE username='TheDoctor'), `group_creator`='TheDoctor', `group_name`='HeroesUnited', `date_created`= CURRENT_TIMESTAMP();

Source
INSERT INTO Group
SELECT UUID(),user_id,'TheDoctor','HeroesUnited', CURRENT_TIMESTAMP()
FROM User
WHERE username='TheDoctor'

Related

Auto increment Id value increased by 1 after insert trigger

I have 3 tables as below:
CREATE TABLE `user_dummy` (
`user_id` INT(11) NOT NULL AUTO_INCREMENT,
`user_name` VARCHAR(50) NOT NULL,
`user_email` VARCHAR(100) NOT NULL,
PRIMARY KEY (`user_id`)
)
ENGINE=InnoDB
;
CREATE TABLE `user_role` (
`user_role_id` INT(11) NOT NULL AUTO_INCREMENT,
`user_role_name` VARCHAR(255) NULL DEFAULT NULL,
PRIMARY KEY (`user_role_id`)
)
ENGINE=InnoDB
;
CREATE TABLE `user` (
`user_seq` INT(11) NOT NULL AUTO_INCREMENT,
`user_id` INT(11) NOT NULL,
`user_name` VARCHAR(50) NOT NULL,
`user_email` VARCHAR(100) NOT NULL,
`user_role_id` INT(11) NOT NULL,
PRIMARY KEY (`user_seq`),
INDEX `FKh2wc2dtfdo8maylne7mgubowq` (`user_role_id`),
CONSTRAINT `FKh2wc2dtfdo8maylne7mgubowq` FOREIGN KEY (`user_role_id`) REFERENCES `user_role` (`user_role_id`) ON UPDATE CASCADE ON DELETE CASCADE
)
ENGINE=InnoDB
;
I have created after insert trigger on user table.
i.e., when I insert 1 record into user_dummy table, it will insert records into table user table with all mappings of user_role.
trigger:
CREATE TRIGGER `user_dummy_after_insert` AFTER INSERT ON `user_dummy` FOR EACH ROW BEGIN
INSERT INTO user(user_id, user_name, user_email, user_role_id)
SELECT NEW.user_id, NEW.user_name, NEW.user_email, user_role_id
FROM user_role;
END
Above trigger is able to insert records into user table but the auto_increment value is incremented by 1 after each user_role record.
If you observe user_seq 3 is missing. And after inserting 4 records, auto_increment value set by trigger as 7.
How to fix this ?
Just an alternative: Better you could use the count function to count the total existing records and then increase it by one and assign according as. If you are interested to preserve the insertion sequence.

PHP SQL Inner Join or Union

I want to select different fields from two different tables My users table and my address table as shown below:
my users table:
CREATE TABLE IF NOT EXISTS `users` (
`ID` int(3) NOT NULL AUTO_INCREMENT,
`AccountNumber` int(8) NOT NULL,
`FirstName` text NOT NULL,
`LastName` text NOT NULL,
`EmailAddress` varchar(200) NOT NULL,
`Password` varchar(200) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `AccountNumber` (`AccountNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
INSERT INTO `users` (`ID`, `AccountNumber`, `FirstName`, `LastName`, `EmailAddress`, `Password`) VALUES
(1, 123456, 'test', 'test', 'test#test.ac.uk', '$2y$10$/j9nTE5ugmyrWuV8VNWFxe5iHInqyaTwxt5wDaxyQwPUZTDDjqNKm');
my address table:
CREATE TABLE IF NOT EXISTS `address` (
`AddID` int(4) NOT NULL AUTO_INCREMENT,
`HouseNumber` int(11) NOT NULL,
`StreetName` varchar(200) NOT NULL,
`City` varchar(200) NOT NULL,
`Postcode` varchar(8) NOT NULL,
`AccountNumber` int(8) NOT NULL,
PRIMARY KEY (`AddID`),
KEY `AccountNumber` (`AccountNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
INSERT INTO `address` (`AddID`, `HouseNumber`, `StreetName`, `City`, `Postcode`, `AccountNumber`) VALUES
(1, 123, 'Some Road', 'someCity', 'b66', 123456);
ALTER TABLE `address`
ADD CONSTRAINT `address_ibfk_1` FOREIGN KEY (`AccountNumber`) REFERENCES `users` (`AccountNumber`);
Ive manage to use the following inner join successfully:
SELECT * FROM users INNER JOIN address ON users.AccountNumber=address.AccountNumber
However that also seems to retrieve the auto incremented ID's as well as the password field which i dont want.
I tried union but kept getting the error about different number of columns. How would i change my select statement to only retrieve the FirstName, LastName and EmailAddress from the users table and the HouseNumber, Street, City and Postcode from the address table based on the account number stored in both tables.
Any info will be appreciated
Thanks!
Try this u will get the result
SELECT FirstName,LastName,EmailAddress,HouseNumber,
Street, City, Postcode FROM users
INNER JOIN address ON users.AccountNumber=address.AccountNumber
instead of select *, just list out the columns youd like
SELECT u.FirstName,u.LastName,u.EmailAddress,a.HouseNumber,a.StreetName,a.City,a.Postcode
FROM users u
INNER JOIN address a
ON u.AccountNumber=a.AccountNumber
from there you can add a where statement if you want to limit it down to one AccountNumber:
SELECT u.FirstName,u.LastName,u.EmailAddress,a.HouseNumber,a.StreetName,a.City,a.Postcode
FROM users u
INNER JOIN address a
ON u.AccountNumber=a.AccountNumber
WHERE u.AccountNumber=12345

Mysql : I want to create a trigger which will insert data into user access permission table based on employee table and categories table

I have three tables :- category ,employee and user_access_permission . I want to create a trigger that will fire when new category is added , insert values in user_access_permission for each employee id .default value for user_access is 0.
Category table :-
CREATE TABLE IF NOT EXISTS `categories` (
`category_id` int(11) NOT NULL AUTO_INCREMENT,
`category_name` varchar(100) NOT NULL,
`section_id` int(11) NOT NULL,
UNIQUE KEY `category_id` (`category_id`),
UNIQUE KEY `category_name` (`category_name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Employee table :-
CREATE TABLE IF NOT EXISTS `employee` (
`employee_id` int(11) NOT NULL AUTO_INCREMENT,
`emp_pass` varchar(50) NOT NULL,
`email` varchar(100) NOT NULL,
PRIMARY KEY (`employee_id`),
UNIQUE KEY `email_UNIQUE` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=' ' AUTO_INCREMENT=1;
User Access Permission Table :-
CREATE TABLE IF NOT EXISTS `user_access_permission` (
`uap_id` int(10) NOT NULL AUTO_INCREMENT,
`section_id` int(10) NOT NULL,
`category_id` int(10) NOT NULL,
`employee_id` int(10) NOT NULL,
`access_level` int(10) NOT NULL DEFAULT '0',
PRIMARY KEY (`uap_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
I am writing trigger like this :-
CREATE TRIGGER update_permssion_on_add_category
AFTER INSERT
ON categories FOR EACH ROW
insert into user_access_permission(section_id,category_id,employee_id,access_level) select(new.section_id,new.category_id,employee_id,0) from employee
But I don't get things right. Please Help
You have
select(new.section_id,new.category_id,employee_id,0) from employee
but section_id and category_id come from the category table.
I would suggest changing it to be 'from category' but the problem then is where do you get the employee_id number from? It's not anywhere in the original insert statement for the category table. Unless you decide to have it be some default value every time the trigger is fired.

MySQL joining 2 tables in to one main table

I have 2 tables 'cat' and 'sub_cat' and these two tables should join or something with main table 'product'
I tried all joining methods and non of them gave me right result I want.
I'm sure there is a method. I don't know what to call.
Sample SQL
This is how the last query should be
forget about the normalization theories and every thing and I just want the last query to be like this or mysql method that I can use on this.
cat_id cannot be duplicate
s_id should also cannot be duplicate
like in third row there can be: cat_id but no s_id the s_id should be null
if there is no cat_id and no s_id both should be null like fourth row
p_id can be duplicate
can't use group by or distinct cause it doesn't give null values then as i know
only method i got closer is using left joining both cat and sub_cat to prod table but it gives me duplicate cat_id and s_id and can't use group by or distinct on this cause there should be null values.
here is the test data
CREATE TABLE IF NOT EXISTS `cat` (
`product_id` int(11) DEFAULT NULL,
`cat_id` int(11) DEFAULT NULL,
`cat_name` varchar(10) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `cat` (`product_id`, `cat_id`, `cat_name`) VALUES
(1, 1, 'cat1'),
(2, 2, 'cat2'),
(3, 3, 'cat3'),
(1, 4, 'ca4');
CREATE TABLE IF NOT EXISTS `prod` (
`product_id` int(11) DEFAULT NULL,
`name` varchar(10) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `prod` (`product_id`, `name`) VALUES
(1, 'prod1'),
(2, 'prod2'),
(3, 'pro3'),
(4, 'prod4');
CREATE TABLE IF NOT EXISTS `sub_cat` (
`product_id` int(11) DEFAULT NULL,
`sub_cat_id` int(11) DEFAULT NULL,
`sub_cat_name` varchar(10) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `sub_cat` (`product_id`, `sub_cat_id`, `sub_cat_name`) VALUES
(1, 1, 'sub cat 1'),
(2, 2, 'sub cat 2'),
(1, 3, 'sub3');
I have done a similar thing in this one.prop_cat acts as you Category table,prop_subcat as your subcategory table and property as you product.
CREATE TABLE `prop_cat` (
`pcat_id` int(11) NOT NULL AUTO_INCREMENT,
`pcat_name` varchar(60) DEFAULT NULL,
PRIMARY KEY (`pcat_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
CREATE TABLE `prop_subcat` (
`psubcat_id` int(11) NOT NULL,
`pcat_id` int(11) NOT NULL,
`psubcat_name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`psubcat_id`,`pcat_id`),
KEY `pspc_idx` (`pcat_id`),
CONSTRAINT `catsub` FOREIGN KEY (`pcat_id`) REFERENCES `prop_cat` (`pcat_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `property` (
`prop_id` int(11) NOT NULL AUTO_INCREMENT,
`prop_name` varchar(25) DEFAULT NULL,
`price` double DEFAULT NULL,
`location` varchar(50) DEFAULT NULL,
`image` varchar(60) DEFAULT NULL,
`area` double DEFAULT NULL,
`psubcat_id` int(11) DEFAULT NULL,
`description` text,
PRIMARY KEY (`prop_id`),
KEY `psub_idx` (`psubcat_id`),
CONSTRAINT `psub` FOREIGN KEY (`psubcat_id`) REFERENCES `prop_subcat` (`pcat_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
SELECT
prop_cat.`pcat_id` AS prop_cat_pcat_id,
prop_cat.`pcat_name` AS prop_cat_pcat_name,
prop_subcat.`psubcat_id` AS prop_subcat_psubcat_id,
prop_subcat.`pcat_id` AS prop_subcat_pcat_id,
prop_subcat.`psubcat_name` AS prop_subcat_psubcat_name,
property.`prop_id` AS property_prop_id,
property.`prop_name` AS property_prop_name,
property.`price` AS property_price,
property.`location` AS property_location,
property.`image` AS property_image,
property.`area` AS property_area,
property.`psubcat_id` AS property_psubcat_id,
property.`description` AS property_description
FROM
`prop_cat` prop_cat INNER JOIN `prop_subcat` prop_subcat ON prop_cat.`pcat_id` = prop_subcat.`pcat_id`
INNER JOIN `property` property ON prop_subcat.`pcat_id` = property.`psubcat_id`

Insert error 1241

I have two MySQL INNODB tables 'student' and 'instructor'. They are analogous in almost every single way. I can add arbitrary records into the 'student' table, but not the 'instructor' table. Both tables have the same structure with ID as the primary key.
(ID varchar, name varchar, dept_name, varchar, field4 int)
I have tried queries such as
INSERT INTO instructor VALUES ('12345', 'name', 'computer science', 50000);
INSERT INTO instructor SET ID = 67890, name = 'Polson', dept_name = 'Bioinformatics', salary = 100 ON DUPLICATE KEY SET name = 'Polson', dept_name = 'Bioinformatics', salary = 100;
INSERT INTO instructor (ID) VALUES ('12345');
INSERT INTO instructor (ID) VALUE ('12345');
while all of these queries work with the 'student' table. What is going on?
Here are my create table statements. My user has full permissions. Is there any status query that I should use to look for issues? Thank you!
CREATE TABLE `instructor` (
`ID` varchar(5) NOT NULL DEFAULT '',
`name` varchar(20) DEFAULT NULL,
`dept_name` varchar(25) DEFAULT NULL,
`salary` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`ID`),
KEY `dept_name` (`dept_name`),
CONSTRAINT `instructor_ibfk_1` FOREIGN KEY (`dept_name`) REFERENCES `department` (`dept_name`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `student` (
`ID` varchar(10) NOT NULL DEFAULT '',
`name` varchar(20) DEFAULT NULL,
`dept_name` varchar(25) DEFAULT NULL,
`total_credits` int(11) DEFAULT NULL,
PRIMARY KEY (`ID`),
KEY `dept_name` (`dept_name`),
CONSTRAINT `student_ibfk_1` FOREIGN KEY (`dept_name`) REFERENCES `department` (`dept_name`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE department (
dept_name varchar(25) NOT NULL DEFAULT '',
building varchar(15) DEFAULT NULL,
budget float(12,2) DEFAULT NULL,
PRIMARY KEY (dept_name)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
which contains a record Bioinformatics | DBI | 1000000.00