IF STATEMENT for check if columns in table was filled - mysql

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;

Related

Update column value after insert into table using trigger

I need to update ID column in table after Insert.
ID is varchar and auto-increment. I need to update the value of ID .
Eg.
when we insert a column and the ID value is supposed to be 10, so after the trigger is executed ID value should be updated to 10F.
Based on your comments, you do not need to modify the ID column permanently, which you should never do anyway, but only during certain queries.
To use the ID to distinguish which table a row came from in a join s also a bag idea - IDs should not have any information “encoded” in them: They should be meaningless unique values.
If your design is broken and you absolutely must modify the ID:
select concat(id, 'F') as ID, other_columns from tableA
union all
select ID, other_columns from tableB
or better, introduce an extra column that indicates which table each row came from:
select *, 'F' as origin from tableA
union all
select *, '' as origin from tableB

Insert from two tables where condition

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.

How make insert if select rows == '0' in one query?

In mysql, I have the following:
Structure Table:
id(int primary key)
name(varchar 100 unique)
Values:
id name
1 test
2 test1
I have two queries:
1) SELECT count(*) FROM Table WHERE name='test'
2) if count select rows == 0 second query INSERT INTO Table (name) VALUES ('test')
I know that may be use:
$res = mysql(SELECT count(*) as count FROM Table WHERE name='test');
// where mysql function make query in db
$i = $res -> fetch_assoc();
if($i['count'] < 1 ){$res = mysql(INSERT INTO Table (name) VALUES ('test');}
But I would like know how to make two query in one query.
How do I make one query inside of two?
You can do it with a simple trick, like this:
insert into Table1(name)
select 'test' from dual
where not exists(select 1 from Table1 where name='test');
This will even work if you do not have a primary key on this column.
Explanation: DUAL is a special dummy table that is only referenced here to enable the WHERE clause. You would not be able to have a statement without a FROM clause (like select 'test' where not exists(select 1 from Table1 where name='test')) as it will be incomplete.
Assuming your name column has a UNIQUE constraint, just add IGNORE to the INSERT statement.
INSERT IGNORE INTO Table (name) VALUES ('test')
This will skip the insertion if a record already exists for a particular value and return 0 affected rows. Note that a primary key is also considered a UNIQUE constraint.
If the name column doesn't have such a constraint, I would advice that you add one:
ALTER TABLE `Table` ADD UNIQUE(name)
See also the documentation for INSERT
If you don't need to check whether there is duplication, other's suggestion is good for you. But you need, use 'INSERT' and check error number like this:
mysql_query('INSERT INTO ...');
if (mysql_errno() == 1062)
{
echo "duplicated";
}
else
{
echo "inserted";
}
(I know mysql_XXXX() is deprecated.. just example)

Replacing the single quotes for columns in select statement in SQL Server

I have 2 tables. In table1 I have some rows for persons like this:
PersonX - ID
PersonX - Name
PersonX - Address
PersonY - ID
PersonY - AGE
In 2nd table, above mentioned ID, NAME,ADDRESS,AGE will be columns. And we have detailed data of personX and PersonY here.
Now, main issue is in stored procedure, using cursor, I am storing table1 values ('ID', 'Name', ...) in a variable #Element.
Now I am using select statement in same cursor as below:
SELECT #Element From Table2
I need output of user details like his id, age, address etc. But instead I am getting output as 'ID', 'NAME', 'AGE' etc....
I found that this is because #Element is varchar and has string value, so select statement is executed as below:
SELECT 'ID' from table2.
but all I need is like below
SELECT ID FROM TABLE2
I used replace function its not working for me. Case function, I can't use it because we can't say what data is there for a person in table1. It varies. I need one dynamic statement which can be use for all records. instead of executing case for each record.
SELECT REPLACE(#Element,'''','')
FROM TABLE2
(Still getting 'ID' as output, instead of corresponding value in Table2)
Please help me in this. Hope you understand my explanation
You will need to use dynamic SQL to achieve this, for example:
CREATE TABLE Table1
(
ID INT
,Name VARCHAR(255)
,ADDRESS VARCHAR(255)
)
INSERT Table1 VALUES ('1','Joe Bloggs','Address 1')
INSERT Table1 VALUES ('2','Jane Doe','Address 2')
DECLARE #ColName VARCHAR(255) = 'ID'
DECLARE #SQL VARCHAR(MAX)
SET #SQL = 'SELECT '+#ColName+','+''''+#ColName+''' FROM TABLE1'
EXEC (#SQL)
In the first column that is returned, is the SQL you want to be able to execute, however in the 2nd column in my query, is what you're doing at the moment. As far as SQL is concerned, your variable is simply storing a value. It does not know you are referring to a column name which is why it simply returns the value.

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.