How to use IF condition in mysql query - mysql

Problem is simple,but it seems that each time I do something wrong in the mysql syntax.
I want to search in a table after a String field. If this field exists, I will increase the number of apparitions.If does not exists, I will add a new row with it.
I am trying to write a query which I will be used with jdbc or hibernate.
I look at many examples in the site, but I fink that I am doing something wrong in the mysql syntax.
For the table:
mysql> select * from phrase;
+----+---------------+-------------------+
| id | phrase_string | apparition_number |
+----+---------------+-------------------+
| 1 | phrase 1 | 2 |
| 2 | phrase 2 | 1 |
| 3 | phrase 3 | 5 |
| 4 | phrase 4 | 6 |
+----+---------------+-------------------+
4 rows in set (0.00 sec)
I use the IF condition from the MYSQL tutorial:
IF search_condition THEN statement_list
[ELSEIF search_condition THEN statement_list] ...
[ELSE statement_list]
END IF
So my query looks like:
**mysql> IF SELECT * FROM phrase WHERE phrase_string="phrase 1" THEN
-> UPDATE phrase SET apparition_number=apparition_number+1
-> ELSE
-> INSERT INTO phrase VALUES(NULL,"phrase 1",1)
-> END IF;**
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF SELECT * FROM phrase WHERE phrase_string="
phrase 1" THEN
UPDATE phrase SET ap' at line 1
Can somebody tell me where I am wrong?
Thank you!

The if syntax could be used only as part of stored procedure.
For this use case insert on duplicate key update can be used. Have a look at this SQL Fiddle.

Related

1064 error in MySQL Command line client when trying to view table but works fine in MySQL Workbench

So i created a database in MySQL Workbench and I am trying to view them on the MySQL Command Line Client because i want to do my queries there instead of the workbench.
Here's whats happening:
mysql> use policestation(crime);
Database changed
mysql> show tables;
+--------------------------------+
| Tables_in_policestation(crime) |
+--------------------------------+
| accused |
| case |
| complainant |
| investigation_officer |
| outcome |
| section_of_law |
+--------------------------------+
6 rows in set (0.04 sec)
mysql> select * from case;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'case' at line 1
The same query works fine in MySQL Workbech. Also it works for all other tables in Command Line Client.
It's b/c Case is a MySQL reserved keyword: https://dev.mysql.com/doc/refman/5.5/en/keywords.html
You'll need to seround reserved keywords with tick marks not quotes.
Example:
SELECT * FROM `case`
Not the same as
SELECT * FROM 'case'
Also here is another helpful link:
Syntax error due to using a reserved word as a table or column name in MySQL

SET a variable in SELECT statement - MySQL

I'm using this code which has an error:
SET #rejects = '';
SELECT *
FROM list
WHERE maker = 1
AND by_ids IN ('10','11')
AND country LIKE '%I%'
AND (
src IS NULL
|| src NOT IN (#rejects)
AND checkSrc(src) = 'yes'
AND SET #rejects = CONCAT(#rejects,',',src)
);
What's causing the issue?
The issue is that you cannot mix select and set in one statement, there'll surely be syntax error:
select*from t where 1 and set#a=1;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'set#a=1' at line 1
If you want to do set within select, use the colon equals syntax. Change this:
select*from t where 1 and set#a=1;
into:
select*,#a:=1 from t where 1;
Here's how you update the variable upon each row:
create table t(id int); insert t values(1),(2),(3);
set#a=0;
select#a:=id from t;
+--------+
| #a:=id |
+--------+
| 1 |
| 2 |
| 3 |
+--------+
And you can even do concat:
set#a='0';
select #a:=concat(#a,',',id)from t;
+-----------------------+
| #a:=concat(#a,',',id) |
+-----------------------+
| 0,1 |
| 0,1,2 |
| 0,1,2,3 |
+-----------------------+
Or concat without the leading 0:
set#a='';
select #a:=concat(#a,if(#a='','',','),id)from t;
+------------------------------------+
| #a:=concat(#a,if(#a='','',','),id) |
+------------------------------------+
| 1 |
| 1,2 |
| 1,2,3 |
+------------------------------------+
However, the manual explicitly states that this is dangerous:
...you should never assign a value to a user variable and read the
value within the same statement...
...you might get the results you expect, but this is not
guaranteed.
...the order of evaluation for expressions involving user variables is
undefined.
This has also been mentioned on Xaprb.
Lastly, if you're doing quirky things like assigning differing value types to the variable and etc, checkout the manual to be sure you understand the intricate mechanisms.
Then you might write your query like this.
SET #rejects = '';
SELECT #rejects = CONCAT(#rejects,',',src) FROM list WHERE maker = 1 AND by_ids IN ('10','11') AND country LIKE '%I%' AND
(src IS NULL OR src NOT IN (#rejects) AND checkSrc(src) = 'yes');
SELECT #rejects;

CONTAINS Not Working in mysql

I am working with CONTAINS, but it is not woking in mysql.
mysql> SELECT * FROM MUTHU;
+---------------------+
| MY |
+---------------------+
| how is your studies |
| how are you there |
| hi there |
+---------------------+
3 rows in set (0.00 sec)
mysql> SELECT * FROM MUTHU CONTAINS ( MY, "how" );
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near '( MY,
"how" )' at line 1
I don't think MYSQL has a function called CONTAINS, try the following query:
SELECT * FROM MUTHU
WHERE MY LIKE '%how%';
I believe contains is used primarily in Xpath/Xquery. A similar function in mysql is INSTR(). The proper code is for using this is:
select * from MUTHU
where INSTR(MY, 'how') > 0;
you missed the Where condition,
try this:
SELECT * FROM MUTHU
Where MY CONTAINS ( MY,"how" );

MySQL extratvalue range, output and parsing issues

I'm learning MySQL. My query is follows:
mysql>select extractvalue(1,1111111111111111111); // 19 1's.
output:
`+-------------------------------------+
| extractvalue(1,1111111111111111111) |
+-------------------------------------+
| 1111111111111111111 |
+-------------------------------------+
1 row in set (0.00 sec)`
But for 20 1's
mysql>select extract(1,11111111111111111111);
+--------------------------------------+
| extractvalue(1,11111111111111111111) |
+--------------------------------------+
| -7335632962598440505 |
+--------------------------------------+
1 row in set (0.00 sec)
And the following show me different errors:
mysql> select extractvalue(rand(),5.5.28));
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near '.28))
' at line 1
mysql> select extractvalue(rand(),version());
ERROR 1105 (HY000): XPATH syntax error: '.28'
Can someone explain me?
I tried out these, it seems to work.
SELECT #rand := RAND();
select extractvalue(1,#rand);
However, extract doesn't seem to work and gives the error. Either way I have not managed to use extract or extractvalue to wrap rand(). Reason could be that extractvalue only returns CDATA. Your intention of application doesn't seem to be supported by this function. It's used on XPATH
for e.g.
Select allhttp://www.blablabla.com/error.php?id=null
and extractvalue(rand(),concat(0x3a,(
select concat(0x3a,username,0x3a,password) from users)))
Found this to be interesting: reference

To cast or not to cast?

I am developing a system using MySQL queries written by another programmer, and am adapting his code.
I have three questions:
1.
One of the queries has this select statement:
SELECT
[...]
AVG(mytable.foo, 1) AS 'myaverage'`,
Is the 1 in AVG(mytable.foo, 1) AS 'myaverage' legitimate? I can find no documentation to support its usage?
2.
The result of this gives me average values to 2 decimal places, why?.
3.
I am using this to create a temp table. So:
(SELECT
[...]
AVG(`mytable`.`foo`, 1) AS `myaverage`,
FROM
[...]
WHERE
[...]
GROUP BY
[...])
UNION
(SELECT
[...]
FROM
[...]
WHERE
[...]
GROUP BY
[...])
) AS `tmptable`
ORDER BY
`tmptable`.`myaverage` DESC
When I sort the table on this column I get output which indicates that this average is being stored as a string, so the result is like:
9.3
11.1
In order to get around this what should I use?
Should I be using CAST or CONVERT, as DECIMAL (which I read is basically binary), BINARY itself, or UNSIGNED?
Or, is there a way to state that myaverage should be an integer when I name it in the AS statement?
Something like:
SELECT
AVG(myaverage) AS `myaverage`, INT(10)
Thanks.
On your last question: can you post the exact MySQL query that you are using?
The result type of a column from a UNION is determined by everything you get back. See http://dev.mysql.com/doc/refman/5.0/en/union.html .
So, even if your AVG() function returns a DOUBLE, the other part of the UNION may still return a string. In which case the column type of the result will be a string.
See the following example:
mysql> select a from (select 19 as a union select '120') c order by a;
+-----+
| a |
+-----+
| 120 |
| 19 |
+-----+
2 rows in set (0.00 sec)
mysql> select a from (select 19 as a union select 120) c order by a;
+-----+
| a |
+-----+
| 19 |
| 120 |
+-----+
2 rows in set (0.00 sec)
Just for anyone who's interested, I must have deleted or changed my predecessors code so this AVG question was incorrect. The correct code was ROUND(AVG(myaverage),1). Apologies to those who scrathed their heads over my stupidity.
on 1.
AVG() accepts exactly one argument, otherwise MySQL will raise an error:
mysql> SELECT AVG( id, 1 ) FROM anytable;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' 1 )' at line 1
http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html#function_avg
Just because I'm curious - what should the second argument do?