Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SOLVE mysql linux bash with coloumn name have "-" & query mysql from file

Tags:

linux

bash

mysql

i have problem with query mysql on linux bash, my query have 2 coloumn with "-" :

mysql -u root -pPass mydb -e "select `work-time` from work where `work-time`> '2013-0-3-07 00:00:00'";

but the result :

bash: work-time: command not found

i know the problem this quote "`" but how solve this ?

I UPDATE MY QUERY

SOLVE query on line :

mysql -u root -pPass mydb -e "select \`work-time\` from work where \`work-time\`> '2013-0-3-07 00:00:00'"

Other Question

If i save my query on file, and query like this

 mysql -u root -pPass mydb < query.sql

got error :

ERROR at line 1: Unknown command '\`'.

SOLVE query from file with standard query

select `work-time` from work where `work-time`> '2013-0-3-07 00:00:00'

save query to file eg. query.sql, and query like this :

mysql -u root -pPass mydb < query.sql
like image 285
user1448102 Avatar asked Nov 03 '22 03:11

user1448102


1 Answers

Mysql and using back ticks in the bash shell

A query like the following will fail since the back tick character has special meaning in the shell:

mysql -u root -pPass mydb -e "select `work-time` from work"

The back tick character must either be escaped or used inside a single quoted string when executing sql from the shell. An example of a single quoted string is the following:

mysql -u root -pPass mydb -e 'select `work-time` from work'

To accomplish the same query using double quotes we would need to escape the back tick character like so:

mysql -u root -pPass mydb -e "select \`work-time\` from work"

I suggest reading up on the difference between double quotes and single quotes in the bash shell.


Example Problem 1:

"select `work-time` from work where `work-time`> '2013-0-3-07 00:00:00'"

The above query will not work. However, you can accomplish this with single quotes but you will need to escape any single quotes that are inside the query like so:

'select `work-time` from work where `work-time`> \'2013-0-3-07 00:00:00\''

Example Problem 2:

"select \`work-time\` from work where \`work-time\`> \'2013-0-3-07 00:00:00\'"

The above query is almost good as you do need to escape the back tick since it has special meaning. However, you do not need to escape the single quotes. With double quotes the query can look like the following:

"select \`work-time\` from work where \`work-time\`> '2013-0-3-07 00:00:00'"

Back ticks inside a SQL file

If you then decided you wanted to put this query in a file and send it to mysql you would no longer need to escape the back tick character since the back tick character has no special meaning inside a sql file. In the file you would just put the standard SQL:

select `work-time` from work where `work-time` > '2013-0-3-07 00:00:00'
like image 89
Brett Avatar answered Nov 09 '22 15:11

Brett