Mysql update field - mysql

I want to update a table's field where said field is equal to something.
For example, I want to do:
UPDATE users SET name = 'John' WHERE name = 'Jane'
Is this valid syntax or will I get an error?

Yes, that should work just fine. I would have thought that the use of double-quotes (instead of single quotes) would have thrown an error, but I just tried it and it worked.
Even though double-quotes will work, the use of the single-quotes is the accepted standard. It's a good idea to get used to using that, just in case you find yourself using an RDBMS (Oracle or MSSQL) that more-tightly enforces ANSI SQL.

Related

Join returns NULL when data that matches is in the table

I'm trying to get results when both tables have the same machine number and there are entries that have the same number in both tables.
Here is what I've tried:
SELECT fehler.*,
'maschine.Maschinen-Typ',
maschine.Auftragsnummer,
maschine.Kunde,
maschine.Liefertermin_Soll
FROM fehler
JOIN maschine
ON ltrim(rtrim('maschine.Maschinen-Nr')) = ltrim(rtrim(fehler.Maschinen_Nr))
The field I'm joining on is a varchar in both cases. I tried without trims but still returns empty
I'm using MariaDB (if that's important).
ON ltrim(rtrim('maschine.Maschinen-Nr')) = ltrim(rtrim(fehler.Maschinen_Nr)) seems wrong...
Is fehler.Maschinen_Nr really the string 'maschine.Maschinen-Nr'?
SELECT fehler.*, `maschine.Maschinen-Typ`, maschine.Auftragsnummer, maschine.Kunde, maschine.Liefertermin_Soll
FROM fehler
JOIN maschine
ON ltrim(rtrim(`maschine.Maschinen-Nr`)) = ltrim(rtrim(`fehler.Maschinen_Nr`))
Last line compared a string to a number. This should be doing it.
Also, use the backtick to reference the column names.
The single quotes are string delimiters. You are comparing fehler.Maschinen_Nr with the string 'maschine.Maschinen-Nr'. In standard SQL you would use double quotes for names (and I think MariaDB allows this, too, certain settings provided). In MariaDB the commonly used name qualifier is the backtick:
SELECT fehler.*,
`maschine.Maschinen-Typ`,
maschine.Auftragsnummer,
maschine.Kunde,
maschine.Liefertermin_Soll
FROM fehler
JOIN maschine
ON trim(`maschine.Maschinen-Nr`) = trim(fehler.Maschinen_Nr)
(It would be better of course not to use names with a minus sign or other characters that force you to use name delimiters in the first place.)
As you see, you can use TRIM instead of LTRIM and RTRIM. It would be better, though, not to allow space at the beginning or end when inserting data. Then you wouldn't have to remove them in every query.
Moreover, it seems Maschinen_Nr should be primary key for the table maschine and naturally a foreign key then in table fehler. That would make sure fehler doesn't contain any Maschinen_Nr that not exists exactly so in maschine.
To avoid this problems in future, the convention for DB's is snake case(lowercase_lowercase).
Besides that, posting your DB schema would be really helpfull since i dont guess your data structures.
(For friendly development, is usefull that variables, tables and columns should be written in english)
So with this, what is the error that you get, because if table "maschine" has a column named "Maschinen-Nr" and table "fehler" has a column named "Maschinen_Nr" and the fields match each other, it should be correct
be careful with Maschinen-Nr and Maschinen_Nr. they have - and _ on purpose?
a very blind solution because you dont really tell what is your problem or even your schema is:
SELECT table1Alias.*, table2Alias.column_name, table2Alias.column_name
FROM table1 [table1Alias]
JOIN table2 [table2Alias]
ON ltrim(rtrim(table1Alias.matching_column)) = ltrim(rtrim(table2Alias.matching_column))
where matching_columns are respectively PK and FK or if the data matches both columns [] are optional and if not given, will be consider table_name

Why do all my SQL queries have to be wrapped using the ` symbol?

I have been working on a database for my coursework and have used phpMyAdmin to build it. Now I am working on the queries using the query tool.
When I pick the tables and data I want to query and press "update query" it will generate the query which looks something like this:
SELECT `Customer`.`CustomerName`, `OrderDetails`.`Product`, `OrderDetails`.`QuantityOrdered`
FROM `Customer`
LEFT JOIN `Order` ON `Order`.`Customer` = `Customer`.`CustomerID`
LEFT JOIN `OrderDetails` ON `OrderDetails`.`Order` = `Order`.`OrderID`
This works fine and gives me the results I was expecting. However when I try and write my own query and put something like "SELECT Customer.CustomerName," WITHOUT the ' symbol it won't work and just throws up an error message.
Must I always wrap them using the ' symbol for the query to work?
Forward quotes are used to escape object names in MySQL. You don't have to use them unless you use names that wouldn't be valid identifiers - in this case, the table name order is a reserved word, and must be escaped. All the other tables and columns you're using seem to be OK.
Except for the visual nightmare and ability to create horrendous table names, backticks are entirely unnecessary. You will, however, be required to wrap any variables in single quotes.
As you can see from my example below, using backticks is not a requirement with PHPMYADMIN;
The reason it is not working when you remove the backticks is because you have a column called 'order'. Order is a keyword in SQL and therefore cannot be used as a column name without being wrapped in either quotes or backticks.

Column alias is not working for Group, Where and Having in MySQL

I am having the following problem.
I want to execute as sql statement that filters the results with HAVING. However the having is on a column that is calculated from an IF() function inside the select. This way, MySQL server complains that the column inside having clause is unknown!
EX:
SELECT col1,col2,IF(expr1,expr2,expr3) AS `wantedColumn`
FROM....
WHERE ...
HAVING LENGTH(`wantedColumn)>0
It is as mysql cannot understand that the column returned by the if expression is named wantedColumn... If I use other columns it is working correctly. But I need to filter on that. Any suggestions?
Thanks
This is due to mode configurations:
If your database is using the mode 'ONLY_FULL_GROUP_BY', you will not be able to use a column alias in WHERE, GROUP BY or HAVING, it does not work. You have to either repeat the whole expression or use sub query.
In order to know if you are using 'ONLY_FULL GROUP_BY' mode, use the following query:
SELECT ##sql_mode;
If you want to change it to a mode that allows it:
SET SESSION sql_mode =STRICT_TRANS_TABLES;
To know more about SQL modes:
http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html
Answer by comment from Inanda Menezes #Inanda:
Look at it: sqlfiddle.com/#!2/5294e4/6 , I just removed the backticks
from the alias used inside the having and your example worked.
According to mysql documentation you don't need to use backticks on
identifiers that does not have special words or characters. If you use
it, in most of cases, it will not cause your query to fail, but it's
not necessary at all to quote normal identifiers with non-standard
escape. Anyway, it seems to fail when escaping with backsticks a alias
in having clause which uses length function, so just don't escape this
one. – Inanda Menezes

MySQL: REGEXP to remove part of a record

I have a table "locales" with a column named "name". The records in name always begin with a number of characters folowed by an underscore (ie "foo_", "bar_"...). The record can have more then one underscore and the pattern before the underscore may be repeated (ie "foo_bar_", "foo_foo_").
How, with a simple query, can I get rid of everything before the first underscore including the first underscore itself?
I know how to do this in PHP, but I cannot understand how to do it in MySQL.
SELECT LOCATE('_', 'foo_bar_') ... will give you the location of the first underscore and SUBSTR('foo_bar_', LOCATE('_', 'foo_bar_')) will give you the substring starting from the first underscore. If you want to get rid of that one, too, increment the locate-value by one.
If you now want to replace the values in the tables itself, you can do this with an update-statement like UPDATE table SET column = SUBSTR(column, LOCATE('_', column)).
select substring('foo_bar_text' from locate('_','foo_bar_text'))
MySQL REGEXs can only match data, they can't do replacements. You'd need to do the replacing client-side in your PHP script, or use standard string operations in MySQL to do the changes.
UPDATE sometable SET somefield=RIGHT(LENGTH(somefield) - LOCATE('_', somefield));
Probably got some off-by-one errors in there, but that's the basic way of going about it.

Replacing a formatted string in MySql

I'm trying to replace all instances of an old BB tag markup in a MySql database with a newer, slightly different one.
The old format is this...
[youtube:********]{Video ID}[/youtube:********]
Which I would like to replace with this...
[youtube:********]http://www.youtube.com/watch?v={Video ID}[/youtube:********]
Where the *'s are a random string of alpha-numeric characters. So simply REPLACE(feild, '[youtube:********]', '[youtube:********]http://www.youtube.com?watch?v= won't do unfortunately.
All the clumsy attempts I've made using REPLACE() and INSTR() have resulted in nasty things like [b]Bold Text[/b]http://www.youtube.com/watch?v=
Is there a way to do this kind of pattern replacement in MySql? Possibly with Regular Expressions?
Thank you.
Is this what you tried?
UPDATE table SET Field = REPLACE(Field,']{',']http://www.youtube.com/watch?v={')
This would depend if there isnt any other occurences of ']{'
EDIT: You may also want to try:
UPDATE table SET Field = LEFT(Field,#) + 'http://www.youtube.com/watch?v='+
RIGHT(Field,(Char_Length(Field)-#);
Just check the syntax with MYSQl docs. Char_LNEGTH() may need to be LENGTH() - im sure you get the idea