Postgres SQL Joins for Many To Many Relationship - node.js

right now I am "learning" Postgres SQL. I have 3 tables:
1) User: userId
2) Stack :stackId
3) User_Stack: userId, stackId
Now I want to fetch all stacks belonging to one user, given the userId. I understand I need to use Joins, but thats were I get stuck... I try it like this:
SELECT * FROM "Stack" LEFT OUTER JOIN "User_Stack" ON ('User_Stack.stackId' = 'Stack.stackId') WHERE "userId" = '590855';
Error: The returned data is empty.
PS: Is there any GUI Query builder out there ? Or do you have any other tips how to systematically create queries ?
EDIT: If I change the query to this:
SELECT * FROM "Stack" INNER JOIN "User_Stack" ON (User_Stack.stackId = Stack.stackId) WHERE "userId" = '590855';
I get the following error:
Kernel error: ERROR: missing FROM-clause entry for table "user_stack"
LINE 1: SELECT * FROM "Stack" INNER JOIN "User_Stack" ON (User_Stack...

Your main error is in the join. If you do 'something' = 'other' you're comparing string literals, not getting anything from the database. So this will always return false. You will want to compare table1.field1 = table2.field2
Another thing is the LEFT OUTER JOIN. I'm pretty sure you want an INNER JOIN since you want only fields that exist in the other table.
Also don't use double quotes for fields and table names since then the database will require case sensitivity and usually it's not good to have case sensitive names. You can use them with lowercase names if you need and always create them in lowercase.
Numbers also don't need to be quoted, it will just cause more processing when the system has to convert them from text to numbers.

Related

Postgresql jsonb -> invalid reference to FROM-clause entry for table "mt"

So I'm trying to inner join multiple tables in order to bind jsonb with a name. But I'm getting this error.
ERROR: invalid reference to FROM-clause entry for table "mt"
Find the recreational fiddle of the problem below.
SELECT test,jsonb_build_object(
'myData_updated',
json_agg(elems || jsonb_build_object('product_name', po.name))
)
FROM mainTable mt,
jsonb_array_elements(mt.myData) AS heading_elems,
jsonb_array_elements(heading_elems -> 'pItems') AS elems
JOIN products po ON (elems ->> 'pid' )::int = po.pid
INNER JOIN clients client ON client.client_id = mt.client_id
INNER JOIN projects project on project.project_id = mt.project_id
https://dbfiddle.uk/?rdbms=postgres_10&fiddle=63e5b8a49940bb50b5bb7985a947c09e
I have tried removing alias i still get the same error. Quick googling says it is caused because of JOIN & ", delimited FROM" query
The syntax
table,
json_array_elements()
is the shortcut for
table CROSS JOIN LATERAL
json_array_elements()
So with the , syntax you used is an implicit join. After that, with using INNER JOIN you are using an explicit join. The mix is not always working, so replace the implicit syntax with an explicit one and it works.
demo:db<>fiddle
Beside this, the used function json_agg() is an aggregate, so if you want to get other columns like test you have to do a GROUP BY and/or use more aggregate functions on these columns.

Maximo Conditional expression manager/Sql Query Builder

Can somebody help me in converting below mentioned query in to Maximo's where clause:
select distinct workorder.wonum from workorder inner join [assignment]
On workorder.wonum=[assignment].wonum
inner join amcrew
On amcrew.amcrew=[assignment].amcrew
inner join amcrewlabor
On amcrewlabor.amcrew=amcrew.amcrew
inner join labor
On amcrewlabor.laborcode=labor.laborcode
inner join person
on labor.laborcode=person.personid where amcrewlabor.laborcode='KELLYB'
KELLYB is PERSONID used here for just reference.
If you are using a custom search query in Maximo, you can try prepending your with in (your query)
For example, if you're in Maximo's work order tracking module, the application uses select * from workorder by default. Any time you add a search filter such as work order number (wonum), then the query appends to run a query as select * from workorder where wonum = '123' if 123 is the work order number you entered.
Your where clause might look something like this:
wonum in (
select distinct workorder.wonum
from workorder
join assignment on workorder.wonum=assignment.wonum
join amcrew on amcrew.amcrew=assignment.amcrew
join amcrewlabor on amcrewlabor.amcrew=amcrew.amcrew
join labor on amcrewlabor.laborcode=labor.laborcode
join person on labor.laborcode=person.personid
where amcrewlabor.laborcode='KELLYB'
)
The SQL that is generated in Microsoft Access will not necessarily work in Maximo without some modification.

NodeJS Sequelize and FindAll with Include and constraints

I am trying to use the Include capabilities in the Find all to Eager load the data i need in a single query. My issue is that all the includes are LEFT OUTER JOIN ... which is good but i am not seeing a way to add additional constraints to that LEFT OUTER JOIN.
My query would look something like:
Matches.findAll(
{where: ["match.isPublished = ?", true],
include: [RoundMaps,
Locations,
{model: MemberMaps, as: "MemberMaps", where: ["memberMaps.memberUUID = ?", authenticatedUser.uuid]}]})
But this does not seem to be supported ... at least the way i have the syntax written. I cannot add that constraint to the constraints on the LEFT OUTER JOIN ... adding the same constraint to the WHERE clause does not work ... as that gives me only the Matches that the Member is associated with. I want the list of all public Matches and to know which of those that the member has already established an association.
Can it be done?
Sequelize seems to be getting most things done! But still struggling with some things.
Insights welcome!
Cheers
According to your question this is not possible using where clause with LEFT OUTER JOIN.
For this you have to write SQL queries to list of all public Matches and to know which of those that the member has already established an association.
sequelize.query('SELECT * FROM "Matches" LEFT OUTER JOIN "RoundMaps" ON "Matches".id = "RoundMaps".match_id LEFT OUTER JOIN "Locations" ON "Matches".id = "Locations".match_id LEFT OUTER JOIN (SELECT * FROM "MemberMaps" WHERE "MemberMaps".memberUUID = ?) AS "MemberMaps" ON "Matches".id = "MemberMaps".match_id WHERE "Matches".isPublished = ?', null, { raw: true }, [memberUUID,true ]).success(function(myTableRows) {
console.log(myTableRows);
res.send(myTableRows);
});
Executing raw SQL queries in Sequelize
There is an option on INCLUDE that specifies whether the join will be inner or outer: include.require = boolean
When there isn't a where: clause specified, then it defaults to false. But, it gets set to true when a where: is set.
You can explicitly turn that off to fetch all of the results of the findAll().
Unfortunately, the only examples I've seen of this are in the codebase itself, but here it is:
sequelize/test/integration/associations/belongs-to-many.test.js#L167

Cannot link MS Access query with subquery

I have created a query with a subquery in Access, and cannot link it in Excel 2003: when I use the menu Data -> Import External Data -> Import Data... and select the mdb file, the query is not present in the list. If I use the menu Data -> Import External Data -> New Database Query..., I can see my query in the list, but at the end of the import wizard I get this error:
Too few parameters. Expected 2.
My guess is that the query syntax is causing the problem, in fact the query contains a subquery. So, I'll try to describe the query goal and the resulting syntax.
Table Positions
ID (Autonumber, Primary Key)
position (double)
currency_id (long) (references Currency.ID)
portfolio (long)
Table Currency
ID (Autonumber, Primary Key)
code (text)
Query Goal
Join the 2 tables
Filter by portfolio = 1
Filter by currency.code in ("A", "B")
Group by currency and calculate the sum of the positions for each currency group an call the result: sumOfPositions
Calculate abs(sumOfPositions) on each currency group
Calculate the sum of the previous results as a single result
Query
The query without the final sum can be created using the Design View. The resulting SQL is:
SELECT Currency.code, Sum(Positions.position) AS SumOfposition
FROM [Currency] INNER JOIN Positions ON Currency.ID = Positions.currency_id
WHERE (((Positions.portfolio)=1))
GROUP BY Currency.code
HAVING (((Currency.code) In ("A","B")));
in order to calculate the final SUM I did the following (in the SQL View):
SELECT Sum(Abs([temp].[SumOfposition])) AS sumAbs
FROM [SELECT Currency.code, Sum(Positions.position) AS SumOfposition
FROM [Currency] INNER JOIN Positions ON Currency.ID = Positions.currency_id
WHERE (((Positions.portfolio)=1))
GROUP BY Currency.code
HAVING (((Currency.code) In ("A","B")))]. AS temp;
So, the question is: is there a better way for structuring the query in order to make the export work?
I can't see too much wrong with it, but I would take out some of the junk Access puts in and scale down the query to this, hopefully this should run ok:
SELECT Sum(Abs(A.SumOfPosition)) As SumAbs
FROM (SELECT C.code, Sum(P.position) AS SumOfposition
FROM Currency As C INNER JOIN Positions As P ON C.ID = P.currency_id
WHERE P.portfolio=1
GROUP BY C.code
HAVING C.code In ("A","B")) As A
It might be worth trying to declare your parameters in the MS Access query definition and define their datatypes. This is especially important when you are trying to use the query outside of MS Access itself, since it can't auto-detect the parameter types. This approach is sometimes hit or miss, but worth a shot.
PARAMETERS [[Positions].[portfolio]] Long, [[Currency].[code]] Text ( 255 );
SELECT Sum(Abs([temp].[SumOfposition])) AS sumAbs
FROM [SELECT Currency.code, Sum(Positions.position) AS SumOfposition
FROM [Currency] INNER JOIN Positions ON Currency.ID = Positions.currency_id
WHERE (((Positions.portfolio)=1))
GROUP BY Currency.code
HAVING (((Currency.code) In ("A","B")))]. AS temp;
I have solved my problems thanks to the fact that the outer query is doing a trivial sum. When choosing New Database Query... in Excel, at the end of the process, after pressing Finish, an Import Data form pops up, asking
Where do you want to put the data?
you can click on Create a PivotTable report... . If you define the PivotTable properly, Excel will display only the outer sum.

Subsonic 3 Simple Query inner join sql syntax

I want to perform a simple join on two tables (BusinessUnit and UserBusinessUnit), so I can get a list of all BusinessUnits allocated to a given user.
The first attempt works, but there's no override of Select which allows me to restrict the columns returned (I get all columns from both tables):
var db = new KensDB();
SqlQuery query = db.Select
.From<BusinessUnit>()
.InnerJoin<UserBusinessUnit>( BusinessUnitTable.IdColumn, UserBusinessUnitTable.BusinessUnitIdColumn )
.Where( BusinessUnitTable.RecordStatusColumn ).IsEqualTo( 1 )
.And( UserBusinessUnitTable.UserIdColumn ).IsEqualTo( userId );
The second attept allows the column name restriction, but the generated sql contains pluralised table names (?)
SqlQuery query = new Select( new string[] { BusinessUnitTable.IdColumn, BusinessUnitTable.NameColumn } )
.From<BusinessUnit>()
.InnerJoin<UserBusinessUnit>( BusinessUnitTable.IdColumn, UserBusinessUnitTable.BusinessUnitIdColumn )
.Where( BusinessUnitTable.RecordStatusColumn ).IsEqualTo( 1 )
.And( UserBusinessUnitTable.UserIdColumn ).IsEqualTo( userId );
Produces...
SELECT [BusinessUnits].[Id], [BusinessUnits].[Name]
FROM [BusinessUnits]
INNER JOIN [UserBusinessUnits]
ON [BusinessUnits].[Id] = [UserBusinessUnits].[BusinessUnitId]
WHERE [BusinessUnits].[RecordStatus] = #0
AND [UserBusinessUnits].[UserId] = #1
So, two questions:
- How do I restrict the columns returned in method 1?
- Why does method 2 pluralise the column names in the generated SQL (and can I get round this?)
I'm using 3.0.0.3...
So far my experience with 3.0.0.3 suggests that this is not possible yet with the query tool, although it is with version 2.
I think the preferred method (so far) with version 3 is to use a linq query with something like:
var busUnits = from b in BusinessUnit.All()
join u in UserBusinessUnit.All() on b.Id equals u.BusinessUnitId
select b;
I ran into the pluralized table names myself, but it was because I'd only re-run one template after making schema changes.
Once I re-ran all the templates, the plural table names went away.
Try re-running all 4 templates and see if that solves it for you.

Resources