How to use select statement to insert values on a table - mysql

I am trying to insert theses values to my table student but I have an error
insert into student(first_name,last_name,student_number,professor_id)
values(Eden,Yuan,323744573,
select professor_id from PROFESSORS where professor_name = 'Chu ')
I get an error
saying missing expression

you can use this way (assuming that professor_id is the column you need)
insert into student(first_name,last_name,student_number,professor_id)
select 'Eden', 'Eden', 323744573, column_professor_id
from PROFESSORS where professor_name = 'Chu ' ;
(In your query is missing the column in the select )

Related

INSERT ... SELECT(insert many rows)

i want to insert the scholar's id to the tblinbox. Here is my query:
$sql = "INSERT INTO tblinbox VALUES ('','$sender','$type','$subject','$LRN','$content','$date', '$newyearLevel','','$userType','THIS_IS_FOR_THE_ID_OF_THE_SCHOLAR')
SELECT id FROM tblscholar WHERE schoYear = '$newyearLevel'";
my problem is,it is not inserting. what will i change in my query?
INSERT ... SELECT syntax does not allow for VALUES declaration. The values ARE the results returned from the SELECT.
See the documentation here: http://dev.mysql.com/doc/refman/5.6/en/insert-select.html
I honestly am not fully sure what you are trying to do with your insert. If you are trying to insert the same values held in your variables for each id value from the tblscholar table then perhaps you need to do something like this:
INSERT INTO tblinbox
/*
maybe add column definitions here to make it clearer
column definitions could look like this:
(
someField,
type,
subject,
LRN,
content,
`date`,
newyearLevel,
someOtherField,
userType,
id
)
*/
SELECT
'',
'$sender',
'$type',
'$subject',
'$LRN',
'$content',
'$date',
'$newyearLevel',
'',
'$userType',
id
FROM tblscholar
WHERE schoYear = '$newyearLevel'
An INSERT statement supports either a VALUES clause followed by a row of values, or else a SELECT query with columns to match the columns of the table you want to insert into.
But not both!
But you can add constant values into your SELECT query:
$sql = "INSERT INTO tblinbox
SELECT '','$sender','$type','$subject','$LRN','$content','$date',
'$newyearLevel','','$userType', id
FROM tblscholar WHERE schoYear = '$newyearLevel'";
considering id is the first column in your insert statement, try this
$sql = "INSERT INTO tblinbox VALUES ((SELECT id FROM tblscholar WHERE schoYear = '$newyearLevel'),'$sender','$type','$subject','$LRN','$content','$date', '$newyearLevel','','$userType')";
You can insert values either fetching values form another table or providing values as follows:
Way 1:
INSERT INTO tblinbox(coloumn_name1,coloumn_name2) VALUES (value1,value2);
Way 2:
INSERT INTO tblinbox(coloumn_name1,coloumn_name2) SELECT value1,value2 from tblscholer where schoYear= '$newyearLevel';

Insert Into table If similar value exists in another existing table (not a foreign key)

I'm trying to insert an "Item order" in a table called AsksFor and I want to make sure the Item and ItemManufacturer exists in the table Sells. However I keep getting "syntax error, unexpected if, expecting END_OF_INPUT or ';'" for using the IF. Anyone know any other ways to write this for MySQL?
INSERT INTO AsksFor (Username, ItemName, ItemManufacturer)
VALUES ('Harish', 'zkoxtlv93', 'tbzrt93')
IF EXISTS(SELECT ItemName, ItemManufacturer
FROM Sells
WHERE Sells.ItemName = VALUES(ItemName)
AND Sells.ItemManufacturer = VALUES(ItemManufacturer));
EXISTS clause is not availaible for MySQL . Anyways you don't need it , the AND condition in WHERE clause performs the checking part whether values exists in source table Sells.
Try this
INSERT INTO AsksFor (Username, ItemName, ItemManufacturer)
SELECT DISTINCT 'Harish',ItemName, ItemManufacturer
FROM Sells
WHERE ItemName='zkoxtlv93' AND ItemManufacturer='tbzrt93'

How can i get values from 3 different columns into single column in another table

select cons_id,teh_id,local_id,panchayt_id,war_id,ha_id from b...;
select rep_value_id from val;`
i need to get the above values into single column in another table.
how can i solve it by a query or using stored procedure.
You can do something like this in oracle sql .
Insert into VAL_TABLE (ID,COMMON_FIELD) values (VAL_TABLE_ID.nextval, ( SELECT CONS_ID || TECH_ID || LOCAL_ID from TABLE_B));
Or in MySQL
Insert into VAL_TABLE (ID,COMMON_FIELD) values (1, ( SELECT concat( id, type, details) from TABLE_B ) );
Try this...
UPDATE my_table SET col1=
(SELECT CONCAT_WS(',',val.rep_value_id,cons_id,teh_id,local_id,panchayt_id,war_id,ha_id)
FROM b,val);

Single query for "INSERT INTO table if column value not found"

How can I use a single query for inserting table when a column value is not found.
eg/ i want to insert new user only when this username not found
what i doing now is issue 1 query to check for existing,
then another query if no existing found. total 2 query
INSERT INTO friends (memberID) SELECT 1 WHERE NOT EXISTS (SELECT memberID FROM friends WHERE memberID = 1)
You just need to add FROM DUAL
INSERT INTO friends
(memberid)
SELECT 1
FROM dual
WHERE NOT EXISTS (SELECT memberid
FROM friends
WHERE memberid = 1)
sql fiddle
How about this:
INSERT INTO YourTable (UserName)
SELECT x
FROM (SELECT 'New User Name' AS x) a
WHERE x NOT IN(SELECT UserName
FROM YourTable)
Since you only want one row with a given value you should enforce that with a UNIQUE constraint on the table, for example:
ALTER TABLE friends ADD UNIQUE (memberID);
After you do that, you can simply add the IGNORE keyword to your insert statements and it won't report an error and it won't insert a duplicate row if it already exists.
INSERT IGNORE INTO friends(memberID) VALUES(1);

INSERT INTO with SubQuery MySQL

I have this Statement:
INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
VALUES (1, 2, (SELECT item_costprice FROM qa_items WHERE item_code = 1));
I'm trying to insert a value copy the same data of item_costprice, but show me the error:
Error Code: 1136. Column count doesn't match value count at row 1
How i can solve this?
Use numeric literals with aliases inside a SELECT statement. No () are necessary around the SELECT component.
INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
SELECT
/* Literal number values with column aliases */
1 AS item_code,
2 AS invoice_code,
item_costprice
FROM qa_items
WHERE item_code = 1;
Note that in context of an INSERT INTO...SELECT, the aliases are not actually necessary and you can just SELECT 1, 2, item_costprice, but in a normal SELECT you'll need the aliases to access the columns returned.
You can just simply e.g.
INSERT INTO modulesToSections (fk_moduleId, fk_sectionId, `order`) VALUES
((SELECT id FROM modules WHERE title="Top bar"),0,-100);
I was disappointed at the "all or nothing" answers. I needed (again) to INSERT some data and SELECT an id from an existing table.
INSERT INTO table1 (id_table2, name) VALUES ((SELECT id FROM table2 LIMIT 1), 'Example');
The sub-select on an INSERT query should use parenthesis in addition to the comma as deliminators.
For those having trouble with using a SELECT within an INSERT I recommend testing your SELECT independently first and ensuring that the correct number of columns match for both queries.
Your insert statement contains too many columns on the left-hand side or not enough columns on the right hand side. The part before the VALUES has 7 columns listed, but the second part after VALUES only has 3 columns returned: 1, 2, then the sub-query only returns 1 column.
EDIT: Well, it did before someone modified the query....
As a sidenote to the good answer of Michael Berkowski:
You can also dynamically add fields (or have them prepared if you're working with php skripts) like so:
INSERT INTO table_a(col1, col2, col3)
SELECT
col1,
col2,
CURRENT_TIMESTAMP()
FROM table_B
WHERE b.col1 = a.col1;
If you need to transfer without adding new data, you can use NULL as a placeholder.
If you have multiple string values you want to add, you can put them into a temporary table and then cross join it with the value you want.
-- Create temp table
CREATE TEMPORARY TABLE NewStrings (
NewString VARCHAR(50)
);
-- Populate temp table
INSERT INTO NewStrings (NewString) VALUES ('Hello'), ('World'), ('Hi');
-- Insert desired rows into permanent table
INSERT INTO PermanentTable (OtherID, NewString)
WITH OtherSelect AS (
SELECT OtherID AS OtherID FROM OtherTable WHERE OtherName = 'Other Name'
)
SELECT os.OtherID, ns.NewString
FROM OtherSelect os, NewStrings ns;
This way, you only have to define the strings in one place, and you only have to do the query in one place. If you used subqueries like I initially did and like Elendurwen and John suggest, you have to type the subquery into every row. But using temporary tables and a CTE in this way, you can write the query only once.