Phalcon: How can i execute my Inner join statement with query builder - phalcon

How can i execute this statement with "Query builder" in phalcon framework and fetch it result:
SELECT Table2.Id
FROM Table2 INNER Table1
WHERE Table1.Id = 1
AND Table2.Name = "Shahin"
AND Table1.Max > Table2.Count;
Tables

Answering a bit late, but let's hope it helps someone else. Phalcon provides an awesome Query builder functionality. You can read more here: https://docs.phalconphp.com/en/latest/api/Phalcon_Mvc_Model_Query_Builder.html
And here is sample join query:
$result = $this->modelsManager->createBuilder()
->columns(array('main.*', 'locations.*'))
->from(array('main' => 'Models\Objects'))
->leftJoin('Models\ObjectLocations', 'locations.foreign_key = main.id', 'locations')
->where('main.active = 1')
->getQuery()->execute();
This will return two objects if query is successful and you selected all the fields (*) from a table:
$result->main
$result->locations
Good thing is those objects allow you to use all model methods. For example
$result->locations->getDistanceBlabla()

Related

Left Join with Partial match SQL Server

I have 2 tables in SQL Server that I am trying to make a left join from so that all records from table1 are shown and any data from table2 is shown if it exists. They are as follows
Table1
id Customername Jobid
--------------------------------
2754444 Jones 123
2854233 Smith 234
Table2
key Location
-----------------------------
FD#2754444 London
FEC#2854233 Liverpool
I can get an inner join query to work as below - but I obviously get only matching records, (which I dont want - I want all records from table1 and any matching values from table2)
This works:
$query = "select distinct table1.id, table1.customername, table1.jobid, table2.location, table2.[key]
from table1
inner join table2
on table1.id= RIGHT([table2].[key],7)"
So changing it to a left join:
This does not work:
$query = "select distinct table1.id, table1.customername, table1.jobid, table2.location, table2.[key]
from table1
left join table2
on table1.id = RIGHT([table2].[key],7)"
It does not return any of the table2 data. Any advice on what I am doing wrong would be very welcome.
Thanks in advance.
I put together a SQL Fiddle to show that your query should work (based on a guess about datatypes). Given that you've wrapped your queries as strings, that raises the question of whether your problem is actually with SQL, or if the ODBC (or whatever) connection is actually returning a parser error rather than a result set. Have you looked at what the db is providing in return? Have you ensured that there is whitespace between each word, even for line breaks (copying your text as-is shows CRs and LFs, but check your code); otherwise, it's quite possible that you're sending SQL Server something like "SELECT * FROMTABLEWHERETHING" rather than "SELECT * FROM TABLE WHERE".
Thank you all for your input. For some reason the RIGHT was not returning anything so I managed to resolve with :
left JOIN [table2] ON [table1].id= substring([key],(CHARINDEX ('#',[key] , 1)+1),7)
Thanks for all your responses.
Jim

MS Access, how to replace a saved query by the full query in a subquery

I have 3 tables:
1 - tblMembers_Info
2 - a junction table
3 - tblCourses
I need to query the members who haven't done a specific course.
After trying to do it manually I gave MS Access "Query Wizard" a try. I ended up with :
A saved query as Query1:
// That one query who did the course
SELECT tblMembers_Info.*, tblCourses.CourseName
FROM tblMembers_Info
INNER JOIN
(tblCourses INNER JOIN tblMembers_Courses
ON tblCourses.IDCourses = tblMembers_Courses.IDCourses)
ON tblMembers_Info.Members_ID = tblMembers_Courses.Members_ID
WHERE (tblCourses.CourseName) In ('NameOftheCourse');
2nd query using the saved Query1:
SELECT tblMembers_Info.Members_ID, tblMembers_Info.FirstName, tblMembers_Info.LastName
FROM tblMembers_Info
LEFT JOIN [Query1]
ON tblMembers_Info.[Members_ID] = Query1.[Members_ID]
WHERE (((Query1.Members_ID) Is Null));
How can I replace the Query1 in the second query with the full query instead of using a QueryDef (the saved query "Query1")?
Also, there's a better way for sure to write that query, I would really appreciate any help.
You can simply replace LEFT JOIN [Query1] with LEFT JOIN (...) AS [Query1] where ... should be the SQL of the first query, without the ending ;.
But I think in your specific case the use of NOT IN might give a better performance to get the same results:
SELECT tblMembers_Info.Members_ID, tblMembers_Info.FirstName, tblMembers_Info.LastName
FROM tblMembers_Info
WHERE tblMembers_Info.[Members_ID] NOT IN (
SELECT tblMembers_Info.[Members_ID]
FROM ((tblMembers_Info
INNER JOIN tblMembers_Courses
ON tblMembers_Info.Members_ID = tblMembers_Courses.Members_ID)
INNER JOIN tblCourses
ON tblCourses.IDCourses = tblMembers_Courses.IDCourses)
WHERE tblCourses.CourseName = 'NameOftheCourse'
);

Update query on temporary table in Linq

Hey guys I am new in Linq and I am trying to convert stored procedures. But I am having a hard time writing update query in LINQ my query in SP is like
UPDATE #tempTable1
SET someColumn = 1
FROM #tempTable1 p, #tempTable2 t2, NonTempTable nt
WHERE t1.id = t2.id
AND t1.id = nt.id
AND nt.status = 'abcd';
I wrote following conversion of above query in LINQ
var Obj = (from t1 in temp1
join t2 in tmp2 on t1.id equals t2.id
join nt in NonTempTable on t2.id equals nt.id
where nt.status == "abcd"
select t1).First();
Obj.somecolumn = 1;
Obj.SubmitChanges();
But I am gettimg following error
Property or indexer 'AnonymousType#1.ProcedureID' cannot be assigned to -- it is read only
I just have database of my application and I am trying to convert stored procedures into LINQ using LINQPad
Can anyone tell me how to write above query to Linq? What more do I need to do this?
You have to create an entity from your tempTable1, tempTable2 and NonTempTable. Then you should be able to work with the data from these tables by means of Linq. See http://msdn.microsoft.com/en-us/data/ff830362.aspx how to create models.
After you create it, you can update your records or proper record and save changes to database
var result = (from row in model.JoinedTable
where row.status == "abcd"
select row).First();
result.someColumn = "1";
model.SaveChanges();
Linq is for querying, not updating. In order to update data you need to choose a framework (or find out what the main project team is using) that is designed to do that - Entity Framework, LinqToSQL, or plain old ADO.NET (SQlCommand + SqlConnection, etc.).
There is no built-in mechanism within Linq to update data in memory, let alone propagate changes to a data source. Even with Entity Framework - you can use Linq to get the object(s) you want to update, but the actual updating does not use Linq at all, just property setters and methods like SaveChanges() which you have in your example.
Finally found a workaround for my above question which is following
var Obj = (from t1 in temp1
join t2 in tmp2 on t1.id equals t2.id
join nt in NonTempTable on t2.id equals nt.id
where nt.status == "abcd"
select t1).First();
var anatherObj = (from o in Obj
select new { o.nonUpdatedColumn1, o.nonUpdatedColumn2, o.nonUpdatedColumn3, o.someColumn = 1});
And got the updated temporary table in "anatherObj"

Strange UPDATE syntax in MS Access 2003

I've got an Access application with an update query with the following syntax:
UPDATE TABLE1, TABLE2 SET
TABLE2.VALUE1 = TABLE1.VALUE1,
TABLE2.VALUE2 = TABLE1.VALUE2,
TABLE2.VALUE3 = TABLE1.VALUE3,
TABLE2.VALUE4 = TABLE1.VALUE4
The query is working but I do not understand what's going on here.
I'm trying to convert this query to SQL Server.
Can somebody please explain what this query does? My guess is that it's a special Access syntax.
Thanks,
Sven
It uses the older implicit JOIN syntax, although SQL Server should understand that syntax too.
It's INNER JOINing table1 and table2, then moving the values from table1 to table2. Because of the lack of JOIN conditions, if table1 has more than 1 row it may have unpredictable results.
Essentially it is:
UPDATE Table1 INNER JOIN Table2 <<ON Missing Conditions Here>>
SET Table2.Value1 = Table1.Value1
Table2.Value2 = Table1.Value2
Table2.Value3 = Table1.Value3
Table2.Value4 = Table1.Value4
You can convert this to SQL Server with something like this:
UPDATE Table2
SET Table2.Value1 = Table1.Value1
Table2.Value2 = Table1.Value2
Table2.Value3 = Table1.Value3
Table2.Value4 = Table1.Value4
FROM Table1 INNER JOIN Table2 <<ON Missing Conditions Here>>
Every field from TABLE2 will override corresponded field from TABLE1 with records from TABLE1 one by one. Result will be TABLE2 with all replaced records by last row from TABLE1. If TABLE1 has no records - no changes happens.
Sorry for my english.
And... it is SQL.
Try to avoid the "UPDATE with join" syntax in SQL Server. It is completely non-standard SQL but more seriously it gives unpredictable results without any error or warning if the joining criteria is not correct. Use the MERGE statement instead or use the standard version of the UPDATE statement (with a subquery) if you can.

Why doesn't this SQL statement work?

SELECT * FROM table1, table2
WHERE table1.user_id = table2.id
AND table1.content = news
AND table1.content_id = 1
that wont work. cant u have two "AND" in a sql statement??
//Tomek
you probably want to quote 'news' as a string...
You also probably want to use an inner join instead (much more efficient)
SELECT * FROM table1
INNER JOIN table2 ON table1.user_id = table2.id
WHERE table1.content = 'news'
AND table1.content_id = 1
news is what? Some sort of parameter? Value of the field? A word which should occur in the field? Most likely your syntax is wrong, see W3Schools WHERE and W3Schools AND/OR operators pages for more information.
let me rewrite that for you with a JOIN statement since it is not 1995 anymore, you also need quotes around news
SELECT * FROM table1 t1
inner join table2 t2 on t1.user_id = t2.id
AND t1.content = 'news'
AND t1.content_id = 1
First let's start with getting rid of that old-style join so that the join and where clauses are clearly separated to make understanding much easier.
SELECT * FROM table1 t1.
JOIN table2 t2
ON t1.user_id = t2.id
WHERE t1.content = news
AND t1.content_id = 1
Now let's discuss what the problem might be. First what error are you receiving as this could be perfectly acceptable syntax? Could the problem be that you have not noted which table news is to come from? If it is in both tables you could be getting an error there. If news is meant to be the value of the column you would want it to be 'news' instead of news. It could also simply be that no records meet your conditions.
Further it is a bad practice to ever use select * and it should never be used in a join as you are returning at least one field twice and that is wasteful of both database and network resources. Always specify only the columns you need. This wastes lots of resources every day when lazy programmers do this in every query.
What do table1 and table2 look like? Can you paste a create script?
I would STRONGLY recommend to use the proper JOIN syntax:
select * from table1
inner join table2 on table1.user_id = table2.id
......
what datatypes is "table1.content" ?
You can most definitely have a lot more than just 2 AND statements in a SQL query - any database that really support any of the SQL-xx standards will support this...
I liked cmartin's response. Also, you can use more than one AND, if needed.