I have 3 tables
Table 1 EIN columns :
id, name, plate,in_datetime,time,image-name.
Table 2 EOUT columns :
id, name, plate, out_datetime, time, image-name.
Table 3 recon columns :
id, plate,in_datetime,in_entry_id,out_datetime, out_entry_id,Processed, duration.
I need to get table 1 and table 2 values into table 3 columns using where condition.
I am using the below query:
INSERT INTO recon (id,EIN.plate,EIN.in_datetime, EIN.id, EOUT.out_datetime, EOUT.id,null, null)
SELECT EIN.RegistrationMark,EIN.datetime,EIN.id, EOUT.date,EOUT.id FROM EIN_anpr_vega as EIN, EOUT_anpr_vega as EOUT
where EIN.plate = EOUT.plate
and EIN.in_datetime = EOUT.out_datetime
I am getting an error near null, null. below is the error.
for the right syntax to use near 'null, null
In your column names you cant write null
INSERT INTO recon (id,EIN.plate,EIN.in_datetime, EIN.id, EOUT.out_datetime, EOUT.id,null, null)
Instead, write the column names and place the nulls in the select. Like this:
INSERT INTO recon (id,EIN.plate,EIN.in_datetime, EIN.id, EOUT.out_datetime, EOUT.id,col1, col2)
SELECT EIN.RegistrationMark,EIN.datetime,EIN.id, EOUT.date,EOUT.id, null, null FROM EarlsdonMSIN_anpr_vega as EIN, EarlsdonMSOUT_anpr_vega as EOUT
where EIN.plate = EOUT.plate
and EIN.in_datetime = EOUT.out_datetime
INSERT INTO recon (id, EIN.plate ...) VALUES ...
The things inside the first () are supposed to be column names for the table recon. (I'm surprised that it did not show a syntax error with EIN.plate.)
Yes, later, null will get into trouble for the same reason -- it is not a column name.
Related
I need a query where if a column from a row was filled, return her, else return another column value in the same table.
This code will insert like a subquery, so, I need that return just only value.
**
Data Base Exemple**
ID
Name
LastName
1
Maria
Nunes
2
Null
Torres
Expected query
SELECT *,
(*new subquery FROM TableName) AS Name,
FROM
Table2.
Expected response
ID
Name
1
Maria
2
Torres
Actually, I get the two values from columns and mount an object with "if statement" separately to check if value is difference of "null"
Try with COALESCE:
SELECT
`ID`,
COALESCE(`Name`, `LastName`) AS `Name`
FROM
`Table2`
You may need to use CASE statement.
SELECT Name, LastName, (case when (Name is null)
THEN
LastName
ELSE
Name
END
)
as data from Table2;
I have a temporary table with some rows:
$query = "CREATE TEMPORARY TABLE {$tn} (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type` varchar(255) NOT NULL,
`title` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB";
I would like to select each row in this table, nulify id, update 'type' (for example) and insert whole selected row into another table (which has the same columns as this table).
I tried this but I am getting an error near SET ( 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 'SET )
foreach ($ids as $id) {//this is each id in temp table
$query = "INSERT INTO $another_table
SELECT * FROM {$tn} WHERE id='$id'
SET id=NULL, type='foo'";
$result = $conn->query($query) or die(mysqli_error($conn));
}
I am not a PHP guru, but this is the syntax you should be following. You may select any number of constants you wish from a table.
INSERT INTO $another_table (id, type, title)
SELECT NULL, 'foo', title
FROM {$tn}
WHERE id = '$id';
This assumes that the other destination table uses the same name for its columns as your first table. If not, then you will have to change the first line of my query.
Note that you should ideally be using a prepared statement here.
If both your tables have the SAME amount of columns, with the same order, and you want to avoid listing each and every column, You could just copy the entry and updated the changed value within the same transaction:
START TRANSACTION;
INSERT INTO table2 SELECT * FROM table1 WHERE id = 57;
UPDATE table2 SET columnYouWantToChange="New Value" WHERE id = 57;
COMMIT;
But maybe you should OUTLINE, what you are trying to achieve? having 2 tables with identical columns "smells" like bad design. Maybe you'd better use the same table along with revision numbers of your data row?
Your SQL is not valid, You have an insert statement with a set statement in it.
All you need is a basic INSERT SELECT this is also no need for the for loop.
INSERT INTO $another_table (id, type, title)
SELECT id, 'foo', title
FROM {$tn}
You can do the set statement as an update after inserting all rows if that is easier to get you head around.
UPDATE $another_table SET id = NULL
https://dev.mysql.com/doc/refman/8.0/en/insert-select.html
FYI if you want SET many or all the columns from a table with the same column names this query run on information_schema will generate the most tedious part of the code for you:
select concat('target.', column_name ,' = ','source.', column_name ,', ') as line
from `columns`
where `columns`.table_name = 'target';
I wanted to add an entry inside a table in SQL database.
For example I have the following Database
CREATE TABLE `distributor_geneology` (
`distributor_gen_id` bigint(20) NOT NULL,
`user_id` varchar(24) NOT NULL,
`id` bigint(20) NOT NULL,
`sponsor_id` bigint(20) NOT NULL,
`rank` tinyint(4) NOT NULL
);
And I want to add an entry in sponsor_id or say id inside a database.
First, I imported the database in my SQL Workbench then In my SQL Workbench, I ran a command select * from distributor_geneology which gave me
Error Code: 1146. Table 'dba_db.distributor_genelogy' doesn't exist
[Question] How can I create/add Entry for ID (or sponsor ID or any other filed)?
One typical way which data would enter a MySQL database is via an INSERT statement:
INSERT INTO distributor_geneology (distributor_gen_id, user_id, id, sponsor_id, rank)
VALUES
(1, 1, 1, 1, 1);
I am inserting 1 everywhere, but you may alter the tuple with the values you want.
Another way to get data into a table is bulk loading via LOAD DATA.
For your first part of your question which is "Add an entry to inside table"
this operation called insertion in the database and the keyword database used to insert data is insert into
It is possible to write the INSERT INTO statement in two ways:
1- specifies both the column names and the values to be inserted
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
you can rearrange the columns orders as you want but must the values be the same order of the columns and you can let any column null if you don't want to insert any data in this column but be careful if you have not null column you must insert in you query
in your case, all the columns you have are not null.
2- if you do not need to specify the column names in the SQL query. make sure the order of the values is in the same order as the columns in the table
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
For your second part of your question which is "Error Code: 1146. Table 'dba_db.distributor_genelogy' doesn't exist"
First, ensure you imported the DB correctly and if yes > write try to use DB name in your query.
select * from DB_Name.Table_Name
Edit:
Try this query format
INSERT INTO distributor_geneology (distributor_gen_id, user_id, id, sponsor_id, rank)
VALUES
(10, '10', 10, 10, 10);
please note I put second value between 2 quotes because you are defining the user_id as varchar which means not an integer so we should put it between qouts
I want some field datas to get inserted from a table(called profile) to another table(services) along with those field datas in the table(to which the values want to be inserted,i.e. services).But I am failing. I am new to MySQL and database queries i need ur help.
$qur = mysql_query("INSERT INTO services(FirstName,LastName,DOB,Mobile,email,CountryCode,Address,State,City,Country,PinCode,altmobnumber,PanCard,AdharCard,ServiceOffering,Fee,FeeDuration,FeeExtraHour,negotiable) select profile.FirstName,profile.LastName,profile.DOB,profile.Mobile,profile.email,profile.CountryCode,profile.Address,profile.State,profile.City,profile.Country,profile.PinCode from profile where id = '$id'")or die(mysql_error());
You need to specify value for every column in your VALUES list. If you do not have any value from the SELECT statement, either use a NULL value for respective field or simply remove it from the VALUES list.
e.g. if you want to insert three values in tbl1 but tbl2 contains only 2 fields, use a NULL value for the third field
INSERT INTO tbl1 (a, b, c) SELECT tbl2.a, tbl2.b, NULL FROM tbl2
or if you have a hard coded value,
INSERT INTO tbl1 (a, b, c) SELECT tbl2.a, tbl2.b, some_value FROM tbl2
or simply use only two fields
INSERT INTO tbl1 (a, b) SELECT tbl2.a, tbl2.b FROM tbl2
Now, the VALUES part of your query has 19 fields but your SELECT statement provides only 11 fields. Either add NULL for the last 8 fields for successful execution or remove the last 8 fields from VALUES list
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.