Yii2 Sphinx Left join not working - mysql

I have been trying to use Yii-Sphinx extension and its working fine when i used a simple query but when i try to use left join then it does not work. It returns the below error. I have tested many queries but not working. I am using Yii-Sphinx extension
SQLSTATE[42000]: Syntax error or access violation: 1064 sphinxql: syntax
error, unexpected IDENT, expecting $end near 'LEFT JOIN specs ON specs.id =
listing.specs_id'
The SQL being executed was: SELECT specs.id, listing.title,listing.specs_id,
listing.reg_no, listing.price, listing.status, listing.featured FROM listing
LEFT JOIN specs ON specs.id = listing.specs_id
Error Info: Array
(
[0] => 42000
[1] => 1064
[2] => sphinxql: syntax error, unexpected IDENT, expecting $end near
'LEFT JOIN specs ON specs.id = listing.specs_id'
)
here is my query
SELECT specs.id, listing.title,listing.specs_id, listing.reg_no, listing.price, listing.status, listing.featured FROM listing LEFT JOIN specs ON specs.id = listing.specs_id

I have solved this issue. Here is the detail for anybody who gets stuck in such an issue. Following is my solution with sphinx query builder available in yii2-sphinx extension:
$q = new Query();
$q->from('listing');
$rows = $q->all();
'listing' is the index from the sphinx config file, Join query can be written in sql_query
What i was doing wrong that i was using the simple query rather than query builder and that solved the issue. For example, join query will not work with the below code.
$sql = 'Select * FROM listing';
$rows = Yii::$app->sphinx->createCommand($sql)->queryAll();
Simple query will be executed but the query with any join will return error.

SphinxSearch itself does not support 'JOIN's. It can't run such queries.
Not a problem with yii2-sphinx as such, its how Sphinx Works.
If writing SphinxQL queries directly, can read the SELECT syntax here:
http://sphinxsearch.com/docs/current.html#sphinxql-select
SELECT statement was introduced in version 0.9.9-rc2. It's syntax is based upon regular SQL but adds several Sphinx-specific extensions and has a few omissions (such as (currently) missing support for JOINs).
In general use QueryBuilder
http://www.yiiframework.com/doc-2.0/yii-sphinx-querybuilder.html
as it only offers 'methods' actully supported by Sphinx.

Related

MySQL error 1064 - what is causing it?

I have two similar queries, and the second one is throwing a 1064 error and I can't figure out why. Do you see the issue?
select * from node
join field_data_field_taxonomytopics as tt
on node.nid = tt.entity_id
where tt.bundle = 'magazine_article' and tt.entity_id = 61928;
SELECT
FROM
node node
INNER JOIN field_data_field_taxonomytopics field_data_field_taxonomytopics ON node.nid = field_data_field_taxonomytopics.entity_id
WHERE (field_data_field_taxonomytopics.bundle = 'magazine_article') AND (field_data_field_taxonomytopics.entity_id = '61928')
TL;DR Error #1064 means that MySQL can't understand your command. To fix it:
Read the error message. It tells you exactly where in your command
MySQL got confused. Check the manual. By comparing against what MySQL
expected at that point, the problem is often obvious. Check for
reserved words. If the error occurred on an object identifier, check
that it isn't a reserved word (and, if it is, ensure that it's
properly quoted).
I am guessing the issue here is that in the FROM clause you wrote the table name twice "node node", in addition, you are not selecting anything.
SELECT *
FROM
node node
I hope that will fix the error.

what is wrong with this line of SQL?

SELECT Batch.NumStud
FROM Batch
WHERE CourseID='$courseid'
INNER JOIN Course
ON Batch.CourseID=Course.CourseID"
an error that says mysql_fetch_array(): supplied argument is not a valid MySQL result resource in <b>F:\AppServ\www\anNoECourse.php
is shown.This code was written to feed in data to a google chart.
You put SQL in wrong order (JOIN and WHERE are switched):
SELECT Batch.NumStud
FROM Batch INNER JOIN Course
ON Batch.CourseID = Course.CourseID
WHERE Course.CourseID = '$courseid'
It seems, that your query can be simplified (check your data):
select Batch.NumStud
from Batch
where Batch.CourseID = '$courseid'
I think the error is a bit more complex. Due to the fact that your SQL is invalid, you're not getting a result set. This case is not handled correctly by your PHP code!
So in addition to correcting your SQL as the others have suggested, please make sure to handle the case where you get no results or your query results in an error correctly in your PHP code!
The second part to your solution is as follows:
$result = mysql_query(...);
if ($result)
{
while (...)
...
}
This makes sure that mysql_query actually returned a result set and not false, which it does in case of errors (due to your invalid SQL code, but also in other cases). So just fixing your SQL is not enough to make your script error proof.
But again, do no longer use the mysql_.... functions! They are deprecated.

Rails 3 MySQL 2 reports an error in what looks to be valid SQL syntax

I am trying to use the following bit of code to help in seeding my database. I need to add data continually over development and do not want to have to completely reseed data every time I add something new to the seeds.rb file. So I added the following function to insert the data if it doesn't already exist.
def AddSetting(group, name, value, desc)
Admin::Setting.create({group: group, name: name, value: value, description: desc}) unless Admin::Setting.find_by_sql("SELECT * FROM admin_settings WHERE group = '#{group}' AND name = '#{name}';").exists?
end
AddSetting('google', 'analytics_id', '', 'The ID of your Google Analytics account.')
AddSetting('general', 'page_title', '', '')
AddSetting('general', 'tag_line', '', '')
This function is included in the db/seeds.rb file. Is this the right way to do this?
However I am getting the following error when I try to run it through rake.
rake aborted!
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 'group = 'google' AND name = 'analytics_id'' at line 1: SELECT * FROM admin_settings WHERE group = 'google' AND name = 'analytics_id';
Tasks: TOP => db:seed
(See full trace by running task with --trace)
Process finished with exit code 1
What is confusing me is that I am generating correct SQL as far as I can tell. In fact my code generates the SQL and I pass that to the find_by_sql function for the model, Rails itself can't be changing the SQL, or is it?
SELECT * FROM admin_settings WHERE group = 'google' AND name = 'analytics_id';
I've written a lot of SQL over the years and I've looked through similar questions here. Maybe I've missed something, but I cannot see it.
"group" is a keyword so you can't use it as-is as an identifier, you have to quote it with backticks (for MySQL at least):
SELECT *
FROM admin_settings
WHERE `group` = 'google'
AND name = 'analytics_id'
Any SQL that Rails/ActiveRecord generates will use the quoted version of the column name so I'd guess that you're generating some SQL (or just a snippet of SQL for the WHERE clause) and neglecting to quote the column names.
I'd recommend against using group as a column name, use something else so that you don't have to worry about sprinkling backticks all over the place in your code.
group is an invalid field name if left unquoted, as it is a SQL keyword. To fix, surround it with backticks in your find_by_sql query, so your DB doesn't attempt to interpret it as the GROUP keyword.

Codeigniter Active records complex query

> *1. I need to write this in Active records *
i need to join these 3 tables , but the condition for join is very very selective
$this->db->select(name);
$this->db->from('table0');
$this->db->join('table1','(table1.id=0 AND table0.feild1 = table1.feild1) OR (table1.id=1 AND table0.feild2 = table1.feild2)') // <--- how to write this is my question
i could do a simple join but the main problem is achieving the condition in the join that i have mentioned above.Also this is a small part of a very , very ! big query so i really cant change it back to the native sql query like :
$this->db->query('//entire sql query'); //cant do this, need to write ACTIVE RECORDS
when i write the active records , firebug throws me an error saying :
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 ') OR
any suggestions ?
To be honest, I don't know that it is possible. CI doesn't use true Active Records, so each method has very rigid parameters, and I don't see any that can be tricked into performing the task you need.
What I would try is re-writing your query a bit:
$this->db->select(name);
$this->db->from('table0');
$this->db->join('table1','(table1.id=0 AND table0.feild1 = table1.feild1)', LEFT);
$this->db->join('table1','(table1.id=1 AND table0.feild2 = table1.feild2)', LEFT);
$this->db->where('(table1.id=0 AND table0.feild1 = table1.feild1)');
$this->db->or_where('(table1.id=1 AND table0.feild2 = table1.feild2)');
I believe this query would return the correct values, but you'll certainly want to thoroughly test it. Hope this at least points you in the right direction.

Hibernate Exception on MySQL Cross Join Query

I'm trying to perform a bulk delete of an object, Feature, which has a birdirectional ManyToOne relationship with another class, FeaturesMetadata. I'm having a SQLGrammerException thrown.
The hql I'm using:
String hql = "delete from Feature F where F.featuresMetadata.stateGeoId = :stateGeoId";
Turning on show SQL, the following is generated:
delete from FEATURE cross join FEATURESMETADATA featuresme1_ where STATEGEOID=?
Running the SQL directly in the db client gives this exception:
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 'cross join FEATURESMETADATA featuresme1_ where stategeoid='01'' at line 1
Since the generated SQL is throwing the Exception, I tried changing dialects from MySQL5InnoDBDialect to MySQLInnoDBDialect, but no change.
Can anyone assist?
You may not have joins in such a HQL query. Quote from the reference documentation:
No joins, either implicit or explicit, can be specified in a bulk HQL
query. Sub-queries can be used in the where-clause, where the
subqueries themselves may contain joins.
So I guess something like this should work:
delete from Feature F where F.id in
(select f2.id from Feature f2 where f2.featuresMetadata.stateGeoId = :stateGeoId)
I had the same issue and struggled to find a sensible answer. It seems that, even if you get this approach to work, the SQL generated is highly inefficient (according to what I have read).
So I took a step back and did the following:
List<Properties> props = propDao.findPropertiesByHotelCode(hotel.getCode());
propDao.deleteInBatch(props);
propDao.flush();
Basically rather tan trying to 'delete where', I'm doing a select where and then deleting in batch the set that I retrieved.
Hope this helps.
This is indeed rather poor from Hibernate. But you can solve it like this in a repo: (at least in PostgreSQL, not sure if this syntax should be modified for MySql)
#Modifying
#Query(nativeQuery = true, value = """
DELETE FROM feature f
USING features_metadata fd
WHERE f.features_metadata_id = fd.id AND fd.state_geo_id = :stateGeoId
""")
void deleteByStateGeoIdId(#Param("stateGeoId") UUID stateGeoId);