Rails find_by_sql and parameter for id - mysql

Qucik question, why is the 2nd line of code working and the first not?
Detail.find_by_sql("SELECT * FROM details INNER JOIN players ON players.id = details.player_id WHERE players.team_id = ?", self.id)
Detail.find_by_sql("SELECT * FROM details INNER JOIN players ON players.id = details.player_id WHERE players.team_id = '#{self.id}'")
first line gives me MySQL error, looks like it doesn't pass the parameter to the SQL
Mysql2::Error: 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 '?' at line 1: SELECT * FROM details INNER JOIN players ON players.id = details.player_id WHERE players.team_id = ?

You have to use it like this :
Detail.find_by_sql(["SELECT * FROM details INNER JOIN players ON players.id = details.player_id WHERE players.team_id = ?", self.id])

Wanted to comment on AshwinKumarS's answer, but seems I have no rep points, so I have to post here. He gave the right answer, but with no explanation. Yes, find_by_sql only accepts a single array as its parameter. If you look at the API doc, it gives a wrong method signature (showing the sql parameter as independent of the bind array, but the samples below it are correct). I just wasted, like, an hour, trying to debug a problem caused by this (and of course it shows up as a MySQL syntax error rather than a Rails error - very confusing and frustrating!) Because this method only accepts a single, flat array, if you have many, or a variable number of parameters to pass, do it like this:
Detail.find_by_sql(["SELECT * FROM blah WHERE column1 = ? AND column2 in (?,?,?)", array_of_values].flatten)

find_by_sql supports only sql queries while you are using rails syntax
You should write your query in sql syntax like this:
Detail.find_by_sql("SELECT * FROM details INNER JOIN players ON players.id = details.player_id WHERE players.team_id = #{self.id}")
Or, you can also find it in rails syntax:
Detail.joins(:player).where("players.team_id = ?", self.id)

Related

Symfony2 - subquery within a join error

I would like to use a subquery inside a join, however Symfony2 throws the following error:
Here is my failed attempt:
$query = $em->createQuery(
'SELECT
sc.id AS id,
u.id AS userId,
u.username AS username,
sc_count.upvotes
FROM
myBundle:SuggestedCar sc
INNER JOIN myBundle:User u WITH sc.user_id = u.id
INNER JOIN ( SELECT sc1.user_id, COUNT(sc1.id) AS upvotes
FROM myBundle:SuggestedCar sc1
GROUP BY sc1.user_id
) sc_count WITH u.id = sc_count.user_id'
);
Basically I'm just joining 3 tables and the third one has a count. The query worked when executing it inside the database.
How would it be possible to use a SELECT statement inside a join? Is it a good idea to use raw SQL at this point?
The $em->createQuery() function is expecting DQL as the parameter, not SQL. If you want to execute a raw SQL statement, the syntax is different. You can do it like this:
$sql = "SELECT * FROM my_table";
$em = $this->getDoctrine()->getManager();
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
for more on DQL or querying for objects, see Querying for Object. The biggest difference is DQL will return an object (based on your entity classes in Symfony). The method I posted above will just give you a PDO result. So if you execute raw SQL, don't expect to be able to use the result as an object.
If you want to use raw SQL and still have the result mapped to an object, you can look at the doctrine docs about Result set mapping. In my opinion, this is more work than necessary.

Syntax error in MySQL Join Query

I'm getting a syntax error in MySQL query. Is MySQL and SQL server work differently? Can anyone suggest, what is wrong and where ?
select b.component, d.matter, d.bug, d.timestamp, d.os
from bugs.profiles p, ops_reports.BPR_TAG_DATA d
left join (Select * from bugs where product='test') b
on d.bug=b.bug_id
where d.tagid = 6
and timestamp between "2014-04-21" and "2014-04-24"
and login_name like 'test'
and p.userid = d.user
Error Message 24/04/2014 23:14:10 0:00:00.037 MySQL Database Error: 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 'Select * from bugs where product='Conversions') as b
on (d.bu 1 0
You should not mix implicit and explicit joins. A simple rule: just don't use commas in the from clause.
select b.component, d.matter, d.bug, d.timestamp, d.os
from ops_reports.BPR_TAG_DATA d left join
bugs b
on b.product = 'test' and d.bug = b.bug_id left join
bugs.profiles p
on p.userid = d.user
where d.tagid = 6 and
timestamp between '2014-04-21' and '2014-04-24' and
login_name like 'test';
I also removed the subquery, moving the condition to the on clause. This makes the query more efficient. And changed the delimiters for the date constants to single quotes. Using double quotes for strings can lead to confusion.
EDIT:
All this said, the query in the question looks like it is syntactically correct. I notice that the error message does not refer to this exact query. The query has product='test') b and the error message has product='Conversions') as b. Perhaps there are other differences as well.

what's wrong with this SQL code

I'd like to update all the rows of column URL to Test but I get the following error from the query below
#1064 - 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 'FROM STx AS a LEFT JOIN Routes AS b ON a.RouteID = b.RouteID WHERE a.GroupID ' at line 3
UPDATE Routes SET URL = 'test'
WHERE ID in (
SELECT b.ID
FROM Stx a left JOIN Routes b on a.RouteID = b.RouteID
where a.GroupID = 39 and a.Status = 'Provisioned'
);
There's no syntax error here that I can see. I tested it on MySQL 5.5 and the statement parses fine.
I suspect you might have a non-ASCII whitespace character between b.ID and FROM. Try deleting all the spaces and newlines between those two tokens and then re-insert a plain space.
But that doesn't fix the next problem: MySQL doesn't support UPDATE of a table and SELECT from the same table in a single query. So you can't use a subquery in the way you're dong. That's why other answers are suggesting using a multi-table UPDATE.
Another possibility is that you're not sharing the real query you're running. A lot of people on Stack Overflow ask for help with a query, but they have modified the query to post in their question, to make it simpler or to hide proprietary information.
Please don't just say "it doesn't work." That doesn't help us improve our answers. Give the error message, if any, and be sure to show exactly the statement you're typing.
Why not just:
UPDATE Routes a JOIN Stx b ON (a.routeid = b.routeid)
SET a.URL = 'test'
where b.groupid = 39 and b.status = 'Provisioned'
I created an example SQL Fiddle here.
If you are trying to do something a bit different, can you please either post your real query, or make changes to the data model in the SQL fiddle to show the trouble you are having, and post a link to that.
UPDATE Routes AS b
JOIN Stx AS a ON a.RouteID = b.RouteID
SET b.URL = 'test'
WHERE a.GroupID = 39 and a.Status = 'Provisioned'

MySQL: Syntaxerror when using Join?

Can you find anything wrong with this query?
SELECT * FROM requests
WHERE id = '".$id."'
LEFT JOIN request_data ON (requests.id = request_data.request_id)
GROUP BY requests.id
Been workingon it for a while but can't seem to get it right!
The database looks like this:
-requests
-id
-another column
-and a third one
-request_data
-request_id
-key
-value
EDIT: Oh right, and the error:
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 'LEFT JOIN request_data ON (requests.id = request_data.request_id) GROUP BY ' at line 3
Any ideas?
The WHERE is in the wrong place.
SELECT *
FROM requests
LEFT JOIN request_data ON (requests.id = request_data.request_id)
WHERE id = '".$id."'
You probably don't need a GROUP BY either as the WHERE ensures there will only be one id returned unless in some way you are relying on the hidden columns functionality (which you shouldn't as the results are undefined).

Zend_Db_Select - Joins and Count - Possible Zend Bug?

I'm having an issue getting a COUNT() from a SQL query using Zend_Db_Table_Select, and I think it may be a possible bug because the SQL it should be generating actually works. Here's the Zend Select Query: ($this is a Zend_Db_Table, renamed to table1 in this example)
$select = $this->select();
$select->setIntegrityCheck(false);
// Select Count
$select->from($this, array("COUNT(*) as 'COUNT'"))
->joinLeft('users', 'table1.userID = users.userID')
->joinLeft('table2', 'users.anotherKey = table2.anotherKey');
// Add Where clause after join
$select->where('users.anotherKey = ?', $anotherKeyValue);
This gives the error:
SQLSTATE[42000]: Syntax error or access violation: 1140
Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is
illegal if there is no GROUP BY clause`
However, this query...
SELECT COUNT(*) AS 'count' FROM table1
LEFT JOIN users ON table1.userID = users.userID
LEFT JOIN table2 ON users.anotherKey = table2.anotherKey
WHERE users.anotherKey = [anotherKeyValue]
...returns the expected results with no errors when run against the database. Any ideas whats going on, why the error, and how to get around it?
have you tried to see actual query, that zend_db produce?