I have a syntax question regarding the Rails 3 ActiveRecord::Base.connection.execute method and parameter that i want to use with it. I have been fighting with this for some hours now and just do not seem to find any answers to this specific question on the internet.
The database is MySQL.
I need to create a temporary table through SELECT with IN condition statement, where the list of values against which IN should check, is a parameter - rails Array. The code looks like so:
arr = [1,2,3]
ActiveRecord::Base.connection.execute("CREATE TEMPORARY TABLE things SELECT * FROM objects WHERE objects.id IN #{arr}")
I get a MySQL syntax error!
ActiveRecord::Base.connection.execute("CREATE TEMPORARY TABLE things SELECT * FROM objects WHERE objects.id IN #{(arr)}")
Again MySQL syntax error!
ActiveRecord::Base.connection.execute("CREATE TEMPORARY TABLE things SELECT * FROM objects WHERE objects.id IN (#{arr})")
MySQL syntax error
The above attempts correspond to this question-answer:
How to execute arbitrary parameterized SQL in rails
I even tried to use in the manner like with find_by_sql, but still get an error:
ActiveRecord::Base.connection.execute(["CREATE TEMPORARY TABLE things SELECT * FROM objects WHERE objects.id IN (:ids)",{:ids => arr }]) - obviously, I get an MySQL error.
Am I missing something obvious? Please help! I need this exactly in this way (e.g. create temporary table with exactly such conditions), otherwise a more complicated query based on this one will not work. Thanks!
Here's another option that uses Rails' query sanitization
arr = [1,2,3]
query = "SELECT * FROM objects where id IN (?)"
query = ActiveRecord::Base.send :sanitize_sql_array, [query, arr]
ActiveRecord::Base.connection.execute(query)
If you convert arr.to_s you get "[1, 2, 3]".
I think arr.join(', ') should work.
ActiveRecord::Base.connection.execute("CREATE TEMPORARY TABLE things SELECT * FROM objects WHERE objects.id IN (#{arr.join(', ')})")
Related
I've created a MySQL sproc which returns 3 separate result sets. I'm implementing the npm mysql package downstream to exec the sproc and get a result structured in json with the 3 result sets. I need the ability to filter the json result sets that are returned based on some type of indicator in each result set. For example, if I wanted to get the result set from the json response which deals specifically with Suppliers then I could use some type of js filter similar to this:
var supplierResultSet = mySqlJsonResults.filter(x => x.ResultType === 'SupplierResults');
I think SQL Server provides the ability to include a hard-coded column value in a SQL result set like this:
select
'SupplierResults',
*
from
supplier
However, this approach appears to be invalid in MySQL b/c MySQL Workbench is telling me that the sproc syntax is invalid and won't let me save the changes. Do you know if something like what I'm trying to achieve is possible in MySQL and if not then can you recommend alternative approaches that would help me achieve my ultimate goal of including some type of fixed indicator in each result set to provide a handle for downstream filtering of the json response?
If I followed you correctly, you just need to prefix * with the table name or alias:
select 'SupplierResults' hardcoded, s.* from supplier s
As far as I know, this is the SQL Standard. select * is valid only when no other expression is added in the selec clause; SQL Server is lax about this, but most other databases follow the standard.
It is also a good idea to assign a name to the column that contains the hardcoded value (I named it hardcoded in the above query).
In MySQL you can simply put the * first:
SELECT *, 'SupplierResults'
FROM supplier
Demo on dbfiddle
To be more specific, in your case, in your query you would need to do this
select
'SupplierResults',
supplier.* -- <-- this
from
supplier
Try this
create table a (f1 int);
insert into a values (1);
select 'xxx', f1, a.* from a;
Basically, if there are other fields in select, prefix '*' with table name or alias
I have running an SQL query, which ends up returning * from table ABC.
I am running this in my ruby on rails code by below command:
query:
sql = select * from ABC WHERE <condition>
results = ActiveRecord::Base.connection.exec_query(sql)
I am getting the outputs as results which is of type ActiveRecord::Result
This, I am converting to an array, by using function to_hash provided by ActiveRecord::Result. However, this is an array of Hashes.
Is there a way in which I can convert it to an array of ActiveRecord's
(I need to do further processing with each active record)
For ex: single_result.outdated? (where outdated is a field belonging to another table DEF which is connected to table ABC via single_result.id)
Any help is appreciated. Thanks!
I am trying to update a mysql table with following query using Doctrine. But the table is not get updated. Also below code didnt throw any error. I am totally confused. If i run the query, taken from getDQL() method, in mysql directly it showing 0 rows updated becuase of inproper qoutes. it is working after placed proper qoutes for values in the query. Need help to solve this puzzle.
Since i am new to doctrine, i will use the examples give in querybuilder class file.
$support = $this->createQueryBuilder('p')
->update('gcns', 'g')
->set("g.isActive", "0")
->andWhere("g.issn='".$issn."'");
Do you ever execute the query or are you just building it? You should have something along these lines to execute it:
$support->getQuery()->getSingleScalarResult();
If i run the query, taken from getDQL() method, in mysql directly it showing 0 rows updated becuase of inproper qoutes.
getDQL() returns DQL not SQL, so it will have improper quotesif you try to run it directly inside MySQL, but that's expected.
You shouldn't concatenate $issn into your query. You should use parameters instead:
$qb = $this->createQueryBuilder()
$support = $qb->update('gcns', 'g')
->set('g.isActive', '0')
->andWhere( $qb->expr()->eq('g.issn', ':issn') )
->setParameter( 'issn', $issn )
->getQuery()->getSingleScalarResult()
;
In my table I have a field with data such as 1,61,34, and I need to see if a variable is in that.
So far I have this
SELECT id, name FROM siv_forms WHERE LOCATE(TheVariable, siteIds) > 0
Which works, with the exception that if the siteIds were 2,61,53, and TheVariable was 1, it would return the row as there is a 1 in 61. Is there anyway around this using native MySql, or would I need to just loop the results in PHP and filter the siteIds that way?
I've looked through the list of string functions in MySql and can't see anything that would do what I'm after.
Try with find_in_set function.
SELECT id, name FROM siv_forms WHERE find_in_set(TheVariable, siteIds);
Check Manual for find_in_set function.
I have two tables.
(1) compressors
(2) crankcase_heaters
I'm trying to create a SQL query to do:
Select the compressor.VOLTAGE and compressor.WATT of each compressor.PART_NUMBER
Find the crankcase_heater.PARTNO that has the same voltage and watts.
Add that value into a new field on the compressor table called "CRANKHTR"
Essentially this query will reproduce my compressors table but will have another 'column' called "CRANKHTR".
I'm completely lost on where to even start with this. I tried using the phpmyadmin SQL Query builder but i have no idea where to begin.
Without seeing the exact data structure, it sounds like you need a simple INNER JOIN:
SELECT
`cp`.`VOLTAGE`,
`cp`.`WATT`,
`ch`.`PARTNO` as CRANKHTR
FROM
`compressor` cp
INNER JOIN `crankcase_heaters` ch ON ch.VOLTAGE = cp.VOLTAGE AND ch.WATT = cp.WATT