i have some data in the MySQL table like this:
2017-02-01: 'A': 'K1': 100
2017-02-01: 'A': 'K2': 200
2017-02-01: 'B': 'K1': 300
2017-02-02: 'A': 'K1': 110
2017-02-02: 'A': 'K2': 210
2017-02-02: 'B': 'K1': 310
i need to insert new data only if last (by date) value is not equal with new.
for example: insert new 400 if last [A:K1]<>400
i use 2 queries now for this job, but it's very slow to insert it:
$res=mysql_query("select * from `table` where `col1`='A' and `col2`='K1' order by 'date' desc limit 1");
$tkol=0;
if($res){while($r=mysql_fetch_assoc($res)){$tkol=$r[0]['col3']; break;}}
if($tkol!=$newVal){
$q="INSERT INTO `table` (`date`,`col1`,`col2`,`col3`) VALUES ('2017-02-10','A','K1',$newVal)";
mysql_query($q);
}
how to write my task in 1 mysql-query like "INSERT ... IF ..."?
Please, help me.
Try to use INSERT INTO SELECT syntax:
INSERT INTO `table` (`date`,`col1`,`col2`,`col3`)
SELECT DISTINCT '2017-02-10', 'A', 'K1', $newVal
FROM `table` t1
JOIN (
SELECT MAX(`date`) AS maxdate, `col1`, `col2`
FROM `table`
WHERE `col1` = 'A'
AND `col2` = 'K1'
) t2 ON t1.`col1` = t2.`col1` AND t1.`col2` = t2.`col2` AND t1.`date` = t2.`maxdate`
WHERE t1.`col1` = 'A'
AND t1.`col2` = 'K1'
AND t1.`col3` <> $newVal
use significant column as unique key and use REPLACE instead of INSERT.
OR
You can use insert ... from select ... where oldval <> newval;
select will not have "from" and values will be straightly written into it from webserver.
$q="INSERT INTO `table` (`date`,`col1`,`col2`,`col3`) select ".$date.", ".$a.", ".$b.", ".$c." WHERE not exists (select 1 from `table` where col1 = $a ... and date = select(max) date from table)";
And, remember about input validation!
Related
I need to return the same results of a SELECT request, but with only 1 field change (email).
SELECT `field1`, 'myemail_1#gmail.com' as email, `nom`, `prenom`
FROM my_table
WHERE field1 = 1
AND field2 = 2
LIMIT 200
Return
1,myemail_1#gmail.com,Valjean,Jean
1,myemail_1#gmail.com,Tran,Jerome
1,myemail_1#gmail.com,Doe,John
I need:
1,myemail_1#gmail.com,Valjean,Jean
1,myemail_1#gmail.com,Tran,Jerome
1,myemail_1#gmail.com,Doe,John
1,myemail_2#gmail.com,Valjean,Jean
1,myemail_2#gmail.com,Tran,Jerome
1,myemail_2#gmail.com,Doe,John
In a single request.
Thanks for help
You could use UNION (which will remove duplicates in your case there aren't any duplicates )
SELECT `field1`, 'myemail_1#gmail.com' as email, `nom`, `prenom`
FROM my_table
WHERE field1 = 1
AND field2 = 2
LIMIT 200
UNION
SELECT `field1`, 'myemail_2#gmail.com' as email, `nom`, `prenom`
FROM my_table
WHERE field1 = 1
AND field2 = 2
LIMIT 200
I am currently using the SQL command
Select * from where name='john'
Is it possible to return 20 no matter the query, for example
Select * from where name='john' or return = 20
EDIT
If you have an oracle database you can do something like that:
SELECT *
FROM dual
WHERE 1=0
UNION
SELECT '20'
FROM dual;
check my answer
if exists (Select * from item where ItemName='ABC Daycare1')
begin
Select * from item where ItemName='ABC Daycare1'
end
else
select '20'
Try running this. This should return the top result (which is never 20 due to the custom sort) and then when the name doesn't match a value it returns 'Mark' and 20
SQL
IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp
CREATE TABLE #temp (id int NOT NULL, name varchar(255) NOT NULL)
INSERT INTO #temp (id, name) VALUES (88,'John')
INSERT INTO #temp (id, name) VALUES (20,'Mark')
SELECT TOP 1
*
FROM #temp
WHERE (name = 'Mark' OR name = 'John')
ORDER BY (
CASE
WHEN id = 20 THEN 0 ELSE 1
END) DESC
MySQL - MySQL fiddle
IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp
CREATE TABLE #temp (id int NOT NULL, name varchar(255) NOT NULL)
INSERT INTO #temp (id, name) VALUES (88,'John')
INSERT INTO #temp (id, name) VALUES (20,'Mark')
SELECT
*
FROM temp
WHERE (name = 'Mark' OR name = 'John')
ORDER BY (
CASE
WHEN id = 20 THEN 0 ELSE 1
END) DESC
LIMIT 1
I've been receiving Error Code: 1060. :
Duplicate column name 'NULL'
Duplicate column name '2016-08-04 01:25:06'
Duplicate column name 'john'
However, I need to insert some field with the same value, but SQL is denying and showing the above error. The error is probably sql can't select the same column name, in that case is there other way of writing the code? Below is my current code
INSERT INTO test.testTable SELECT *
FROM (SELECT NULL, 'hello', 'john', '2016-08-04 01:25:06', 'john'
, '2016-08-04 01:25:06', NULL, NULL) AS tmp
WHERE NOT EXISTS (SELECT * FROM test.testTable WHERE message= 'hello' AND created_by = 'john') LIMIT 1
My Column:
(id, message, created_by, created_date, updated_by, updated_date, deleted_by, deleted_date)
Please assist, thanks.
Your duplicate column names are coming from your subquery. You select null, john, and 2016-08-04 01:25:06 multiple times. Provide the columns you are selecting with names/aliases:
INSERT INTO test.testTable
SELECT *
FROM (SELECT NULL as col1, 'hello' as col2,
'john' as col3, '2016-08-04 01:25:06' as col4,
'john' as col5, '2016-08-04 01:25:06' as col6,
NULL as col7, NULL as col8) AS tmp
WHERE NOT EXISTS (SELECT *
FROM test.testTable
WHERE message= 'hello' AND created_by = 'john')
LIMIT 1
Not sure limit 1 is useful here, you are only selecting a single row to potentially insert.
You are using a subquery. Because you don't give the columns aliases, MySQL has to choose aliases for you -- and it chooses the formulas used for the definition.
You can write the query without the subquery:
INSERT INTO test.testTable( . . .)
SELECT NULL, 'hello', 'john', '2016-08-04 01:25:06', 'john',
'2016-08-04 01:25:06', NULL, NULL
FROM dual
WHERE NOT EXISTS (SELECT 1
FROM test.testTable tt
WHERE tt.message = 'hello' AND tt.created_by = 'john'
);
If you do use a subquery in the SELECT, then use correlation clauses in the WHERE subquery:
INSERT INTO test.testTable( . . .)
SELECT *
FROM (SELECT NULL as col1, 'hello' as message, 'john' as created_by,
'2016-08-04 01:25:06' as date, 'john' as col2,
'2016-08-04 01:25:06' as col3, NULL as col4, NULL as col5
) t
WHERE NOT EXISTS (SELECT 1
FROM test.testTable tt
WHERE tt.message = t.message AND
tt.created_by = t.created_by
);
In addition, the LIMIT 1 isn't doing anything because you only have one row.
I don't want this:
SELECT * FROM table
WHERE condition1
OR condition2
OR condition3
Instead I want this:
SELECT * FROM table
WHERE condition1
(if no result)
try condition2
(if no result)
try condition3
How can I write this in MySQL? So if a result is found then don't try the conditions below it.
You can use UNION like this:
SELECT *
FROM table
WHERE condition1
UNION
SELECT *
FROM table
WHERE condition2 AND NOT EXISTS (SELECT 1 FROM table WHERE condition1)
UNION
SELECT *
FROM table
WHERE condition3 AND NOT EXISTS (SELECT 1 FROM table WHERE condition1) AND
NOT EXISTS (SELECT 1 FROM table WHERE condition2)
If first SELECT retuns any rows, then second and third will return no rows. Otherwise, if second SELECT retuns any rows, then third SELECT will return no rows. Otherwise take results from third SELECT.
If your goal is to know which of the conditions was met you could use a UNION query like so:
SELECT *, 1 as `condition` FROM table WHERE <condition1>
UNION
SELECT *, 2 as `condition` FROM table where <condition2>
UNION
...more conditions
SQL Fiddle
MySQL 5.5.32 Schema Setup:
CREATE TABLE Table1
(`id` int, `value` varchar(1))
;
INSERT INTO Table1
(`id`, `value`)
VALUES
(1, 'a'),
(2, 'b'),
(3, 'c'),
(4, 'd'),
(5, 'f'),
(6, 'h'),
(7, 'i')
;
Query 1:
SELECT * FROM Table1
WHERE value =
(case when exists (select 1 from table1 where value='e') then 'e'
when exists (select 1 from table1 where value='a') then 'a'
else 'i' end)
Results:
| ID | VALUE |
|----|-------|
| 1 | a |
You can also try using a WHERE EXISTS statement like so:
SELECT * FROM table
WHERE EXISTS
{Condition 1}
OR EXISTS
{Condition 2}
...more conditions
You can avoid a union like so:
WHERE condition1
OR (condition2 AND NOT EXISTS (SELECT 1 FROM table WHERE condition1))
OR (condition3 AND NOT EXISTS (SELECT 1 FROM table WHERE condition1)
AND NOT EXISTS (SELECT 1 FROM table WHERE condition2)
)
SELECT * FROM table
WHERE val = if(condition1, 'result1', if(condition2, 'result2', if(condition3, 'result3','result')))
I'm trying to insert a record if a sum of 3 user columns from 2 tables exceeds a constant.
I've searched all over, found you can't put user variables in IFs, WHERE's etc. Found you can't put SUMs in IFs, WHERE's etc. I'm at a total loss. Here's an example of my earlier bad code before unsuccessfully trying to use SUMs in WHEREs, if it helps:
SELECT SUM(num1) INTO #mun1 FROM table1 WHERE user = '0';
SELECT SUM(num2) INTO #mun2 FROM table1 WHERE user = '0';
SELECT SUM(num3) INTO #mun3 FROM table2 WHERE column1 = 'd' AND user = '0';
SET #mun4 = #mun1 - #mun2 - #mun3;
INSERT INTO table2 (user, column1, column2) VALUES ('0', 'd', '100') WHERE #mun4 >= 100;
Try this:
INSERT INTO table2 (user, column1, column2)
select '0', 'd', '100'
from dual
where (SELECT SUM(num1 + num2) FROM table1 WHERE user = '0') +
(SELECT SUM(num3) FROM table2 WHERE column1 = 'd' AND user = '0') > 100;
This is a case of the general solution for a "insert if condition" problem:
insert into ... select ... where condition
The select will only return rows if the condition is true, and importantly, will return no rows if false - meaning the insert only happens if the condition is true, otherwise nothing happens.
This is same as #Bohemian's answer, but you got to add a LIMIT clause to stop inserting multiple records, since select clause may return multiple records
INSERT INTO table2 (user, column1, column2)
SELECT '0', 'd', '100'
FROM dual
WHERE
(SELECT SUM(num1 - num2) FROM table1 WHERE user = '0')
(SELECT SUM(num3) FROM table2 WHERE column1 = 'd' AND user = '0') >
100
LIMIT 1