I want to make a insert into 2 tables
visits:
visit_id int | card_id int
registration:
registration_id int | type enum('in','out') | timestamp int | visit_id int
I want something like:
INSERT INTO `visits` as v ,`registration` as v
(v.`visit_id`,v.`card_id`,r.`registration_id`, r.`type`, r.`timestamp`, r.`visit_id`)
VALUES (NULL, 12131141,NULL, UNIX_TIMESTAMP(), v.`visit_id`);
I wonder if its possible
It's not possible with one query as INSERT can only insert data to one table in mysql. You can either
write this as two queries and execute them as a batch
create a stored procedure that would execute two insert command
You can wrap those inserts in transaction if you need to make sure that both queries will write the data.
It seems like the problem you are trying to solve is to get the auto-increment value from the "visits" row to insert into "registration". Am I right?
If so, you can just use the LAST_INSERT_ID() function like this:
INSERT INTO `visits` (`visit_id`,`card_id`)
VALUES (NULL, 12131141);
INSERT INTO `registration` (`registration_id`, `type`, `timestamp`, `visit_id`)
VALUES (NULL, 'in', UNIX_TIMESTAMP(), LAST_INSERT_ID());
You can always do something like this
INSERT IGNORE INTO `table2` VALUES ((select id from table1 where col="value"), 3, 4, 5)
INSERT INTO designation as de,
department as da,
profile as pr
(designation_name,
depart_id,
id,
username,
department,
designation)
select de.designation_name,
de.depart_id,da.id,
pr.username,
pr.department,
pr.designation
from
designation,
department,
profile
de.designation_name='project manager' AND de.id='1' OR
de.depart_id='2' AND de.id='2' OR
da.id='2' OR
pr.username='kapil.purohit' AND pr.id='9' AND pr.status='1' OR
pr.department='1' AND pr.id='9' OR
pr.designation='3' AND pr.id='9' AND pr.status='1'
WHERE
de.id = da.id AND
da.id = pr.id AND
de.id = pr.id AND
ORDER BY de.id DESC
Related
I have 2 tables: users with columns (id,username, password), and user_failed with columns (user_id, failed, time). is there any possible way i can insert into table user_failed by only using username? i try this code but it failed:
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`)
VALUES (SELECT user_id FROM users WHERE username = 'pokemon','',3)
Your SQL query is incorrect for several reasons.
The following should work if I have interpreted your query correctly.
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`)
SELECT id, '', 3 FROM users WHERE username = 'pokemon'
INSERTing into a table from a SELECT does not require VALUES ( ... ). Here is an example of how you would use VALUES ( ... ):
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`)
VALUES (1, '', 3)
Also, your sub query SELECT user_id FROM users WHERE username = 'pokemon','',3 the WHERE clause is invalid. Specifically the '',3 part which I assume is the values you wanted to insert for time and failed.
This will work....you have to add plain parentheses before and after statements.
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`) VALUES ((SELECT user_id FROM users WHERE username = 'pokemon'),'',3)
I am struggling to find a solution need assistance in MySQL script:
Here is my solution design:
Insert values in qa_post (which is in database1) table from test1
(database2)
Get max(postid) from database1.qa_posts (which we
just inserted in step # 1) and then
Insert values in qa_postmetas
(which is in database1) but half of the values will come from database2.test1
Here is my script so far:
INSERT INTO database1.qa_posts (type, categoryid, userid, created, title, content, tags)
(SELECT 'Q_QUEUED', '1', '3', NOW(), f.title, f.img, f.tagsv
FROM database2.test1 f)
LIMIT 1;
INSERT INTO database1.qa_postmetas (postid, title, content)
(select MAX(postid) , 'qa_q_extra', f.URL
from database1.qa_posts b
JOIN database2.test1 f on f.id = b.postid)
LIMIT 1 ;
What wrong:
MAX(postid) is coming from database2.test1 instead of database1.qa_posts
I want to add logic that don't insert in database1.qa_posts until I verify f.URL doesn't exist in database2.test1. If it does exist don't do any insert
MAX(postid) --> MAX(b.postid)
Make a UNIQUE index on test1.URL; then the INSERT will fail. Do INSERT IGNORE so that the failure will be silent.
I want to insert values to a row in my customer table if the Name value I'm providing do not already exist,
After some searching I used this sql query to do it and it does not work :(
IF NOT EXISTS (SELECT Name FROM customer WHERE Name = 'Riyafa')
INSERT INTO customer (`Name`, `Address`, `ContactNo`,`Total_amout`)
VALUES ('Riyafa', 'ABC', '555','1000');
Please instruct me why that is incorrect.
The if statement is only allowed in stored procedures, functions, and triggers. One way you can do this is:
INSERT INTO customer (`Name`, `Address`, `ContactNo`,`Total_amout`)
SELECT name, address, contactno, total_amount
FROM (SELECT 'Riyafa' as name, 'ABC' as address, '555' as contact no, '1000' as total_amount) t
WHERE NOT EXISTS (SELECT 1 FROM customer c WHERE c.name = t.name);
A better approach, however, is to have the database enforce uniqueness on the name. Start by creating a unique index or name:
CREATE UNIQUE INDEX idx_customer_name ON customer(name);
Then use a construct such as on duplicate key update:
INSERT INTO customer (`Name`, `Address`, `ContactNo`,`Total_amout`)
SELECT 'Riyafa' as name, 'ABC' as address, '555' as contact no, '1000' as total_amount
ON DUPLICATE KEY UPDATE Name = VALUES(Name);
The expression ON DUPLICATE KEY UPDATE Name = VALUES(Name) actually doesn't do anything, but it prevents the INSERT from returning an error.
I have fetching record from table named Pizza_Table.
Pizza_table Schema
id | pizza name | pizza_topping_ids
1 | pizza1 |1,2,3
2 | pizza2 |2,3
3 | pizza3 |4,5,6
Actually my functionality is searching pizza based on pizza_topping_ids
I have work allot in this searching. but I can't find proper solution. .
I can't use IN clause for fetching record.
I have tried out :
1)
SELECT *
FROM `pizza_table`
WHERE `pizza_topping_id` REGEXP '[[:<:]]2[[:>:]]'
Problem : fetch all record having value 2
2)
SELECT *
FROM `pizza_table`
WHERE `pizza_topping_id` REGEXP '[[:<:]]1,2,3,4[[:>:]]'
but MySQL returned an empty result set,
If comma separated values are not match to any record then return result which is most having value in topping_id column.
EX: If i have run above query for find out pizza having 1,2,3,4 topping_id, but In database no pizza exist having such topping_id combination then result will be most covered id should be displayed like 'pizza1' having pizza_topping_id 1,2,3.
Sorry for bad English as well as format, but try to understand my problem.
Thanks in advance.
Please help me.
Just try this-
SELECT * FROM `pizza_table` WHERE FIND_IN_SET(2,pizza_topping_id)
OR REGEXP
SELECT * FROM `pizza_table` WHERE pizza_topping_id REGEXP '^2,|,2$|,2,' OR pizza_topping_id =2
Please see the demo : demo
RegEx is slow on very big data sets.
MySQL has a FIND_IN_SET(value, column).
This may not answer your question directly but just only a suggestion :D
First, the rows on table pizza_topping doesn't need to have values separated as commas. It's hard to search for values like this using the current design. The values should be stored in rows not in column.
Consider this following schema,
CREATE TABLE PIZZA
(
PizzaID INT PRIMARY KEY,
NAME VARCHAR(50) UNIQUE,
PRICE DECIMAL(10,2)
);
INSERT INTO PIZZA VALUES (1,'Sunny Side Up Pizza', 120);
INSERT INTO PIZZA VALUES (2,'BBQ Chicken Pizza', 200);
INSERT INTO PIZZA VALUES (3,'Muffuletta Pizza', 175);
INSERT INTO PIZZA VALUES (4,'Caramelized Onion Pizza', 135);
INSERT INTO PIZZA VALUES (5,'Broccoli Deep Dish Pizza', 150);
CREATE TABLE TOPPINGS
(
ToppingID INT PRIMARY KEY,
NAME VARCHAR(50) UNIQUE
);
INSERT INTO TOPPINGS VALUES (1,'Pepperoni');
INSERT INTO TOPPINGS VALUES (2,'Mushroom');
INSERT INTO TOPPINGS VALUES (3,'Sausage');
INSERT INTO TOPPINGS VALUES (4,'Cheese');
INSERT INTO TOPPINGS VALUES (5,'Garlic');
INSERT INTO TOPPINGS VALUES (6,'Ham');
INSERT INTO TOPPINGS VALUES (7,'Tomato Sauce');
And the the records for PIZZA_TOPPING should have multiple rows of ToppingID for each PizzaID.
CREATE TABLE PIZZA_TOPPINGS
(
PizzaID INT,
ToppingID INT,
CONSTRAINT tb_fk1 FOREIGN KEY (PizzaID)
REFERENCES Pizza(PizzaID),
CONSTRAINT tb_fk2 FOREIGN KEY (ToppingID)
REFERENCES TOPPINGS(ToppingID),
CONSTRAINT tb_UQ UNIQUE (PizzaID, ToppingID)
);
INSERT INTO PIZZA_TOPPINGS VALUES (1,1);
INSERT INTO PIZZA_TOPPINGS VALUES (1,2);
INSERT INTO PIZZA_TOPPINGS VALUES (1,3);
INSERT INTO PIZZA_TOPPINGS VALUES (2,4);
INSERT INTO PIZZA_TOPPINGS VALUES (2,5);
INSERT INTO PIZZA_TOPPINGS VALUES (2,6);
INSERT INTO PIZZA_TOPPINGS VALUES (2,7);
INSERT INTO PIZZA_TOPPINGS VALUES (3,1);
INSERT INTO PIZZA_TOPPINGS VALUES (3,3);
INSERT INTO PIZZA_TOPPINGS VALUES (3,5);
INSERT INTO PIZZA_TOPPINGS VALUES (4,2);
INSERT INTO PIZZA_TOPPINGS VALUES (5,1);
INSERT INTO PIZZA_TOPPINGS VALUES (6,7);
INSERT INTO PIZZA_TOPPINGS VALUES (6,1);
The technique of searching records like this is called Relational Division
For example, you want to search for pizza's that have ingredients of: Pepperoni, Mushroom, Sausage.
SELECT a.PIZZAID, a.NAME, a.PRICE
FROM Pizza a
INNER JOIN Pizza_Toppings b
ON a.PizzaID = b.PizzaID
INNER JOIN Toppings c
ON b.ToppingID = c.ToppingID
WHERE c.Name IN ('Pepperoni', 'Mushroom', 'Sausage')
GROUP BY a.PIZZAID, a.NAME, a.PRICE
HAVING COUNT(*) = 3
SQLFiddle Demo
or pizza's that constains of atleast: Pepperoni, Mushroom,
SELECT a.PIZZAID, a.NAME, a.PRICE
FROM Pizza a
INNER JOIN Pizza_Toppings b
ON a.PizzaID = b.PizzaID
INNER JOIN Toppings c
ON b.ToppingID = c.ToppingID
WHERE c.Name IN ('Pepperoni', 'Mushroom')
GROUP BY a.PIZZAID, a.NAME, a.PRICE
HAVING COUNT(*) = 2
SQLFiddle Demo
Theses are much better than using any other functions like FIND_IN_SET, REGEXP, etc..
Try find_in_set of mysql useful in this kind of structures
$id = 2;
$query = $this->db->query("
SELECT *
FROM `pizza_table`
WHERE FIND_IN_SET($id,pizza_topping_id)";
return $query->result();
I want to make a insert into 2 tables
visits:
visit_id int | card_id int
registration:
registration_id int | type enum('in','out') | timestamp int | visit_id int
I want something like:
INSERT INTO `visits` as v ,`registration` as v
(v.`visit_id`,v.`card_id`,r.`registration_id`, r.`type`, r.`timestamp`, r.`visit_id`)
VALUES (NULL, 12131141,NULL, UNIX_TIMESTAMP(), v.`visit_id`);
I wonder if its possible
It's not possible with one query as INSERT can only insert data to one table in mysql. You can either
write this as two queries and execute them as a batch
create a stored procedure that would execute two insert command
You can wrap those inserts in transaction if you need to make sure that both queries will write the data.
It seems like the problem you are trying to solve is to get the auto-increment value from the "visits" row to insert into "registration". Am I right?
If so, you can just use the LAST_INSERT_ID() function like this:
INSERT INTO `visits` (`visit_id`,`card_id`)
VALUES (NULL, 12131141);
INSERT INTO `registration` (`registration_id`, `type`, `timestamp`, `visit_id`)
VALUES (NULL, 'in', UNIX_TIMESTAMP(), LAST_INSERT_ID());
You can always do something like this
INSERT IGNORE INTO `table2` VALUES ((select id from table1 where col="value"), 3, 4, 5)
INSERT INTO designation as de,
department as da,
profile as pr
(designation_name,
depart_id,
id,
username,
department,
designation)
select de.designation_name,
de.depart_id,da.id,
pr.username,
pr.department,
pr.designation
from
designation,
department,
profile
de.designation_name='project manager' AND de.id='1' OR
de.depart_id='2' AND de.id='2' OR
da.id='2' OR
pr.username='kapil.purohit' AND pr.id='9' AND pr.status='1' OR
pr.department='1' AND pr.id='9' OR
pr.designation='3' AND pr.id='9' AND pr.status='1'
WHERE
de.id = da.id AND
da.id = pr.id AND
de.id = pr.id AND
ORDER BY de.id DESC