First Query
SELECT * FROM users WHERE _id = 1
result from query:
{
username: "Test",
nickname: "somename"
}
Second Query
SELECT json_object_agg(permission, true) FROM user_permissions WHERE user_id = 1
result from query:
{
add: true,
delete: true,
somepermission: true
}
Third Query
SELECT array_agg(number) FROM user_phone_numbers WHERE user_id = 1
result from query:
[
00000-0000-000,
11111-1111-111
]
Basically I want to put the result of second and third query into first query so the final result will be
{
username: "Test",
nickname: "somename"
customJSONPermission: {
add: true,
delete: true,
somepermission: true
},
customerArrayPhone: [
00000-0000-000,
11111-1111-111
]
}
How do craft a single SQL command to handle this kind of operation. What kind of keywords or function I should look up?
You can just put all queries in one:
SELECT u.username,
u.nikname,
(SELECT json_object_agg(permission, true) FROM user_permissions WHERE user_id = u._id) AS customJSONPermission,
(SELECT array_agg(number) FROM user_phone_numbers WHERE user_id = u._id) AS customerArrayPhone
FROM users AS u
WHERE u._id = 1
Related
could not find a way to get subqueries to work with sequelize so I used raw querying. I am trying to figure out how to get data from associated tables when I do a raw query. This is what I have tried, but it only returns the data from the primary table and nothing from the associated table:
const rawQuery = `select * from (
select distinct on ("patientId") *
from public."Billings"
order by "patientId","createdAt" desc) as "recentPatientBilling"
where balance > 0;`;
const debtors = await sequelize.query(
rawQuery,
{
model: Billing,
mapToModel: true,
nest: true,
raw: true,
include: [{
model: Patient, attributes: ['id']
}]
}
);
The association is:
Billing.associate = function(models) {
Billing.belongsTo(models.User, {
foreignKey: 'employeeId',
as: 'employee'
});
Billing.belongsTo(models.Patient, {
foreignKey: 'patientId',
as: 'patient'
});
};
Any ideas on how I can get this working? (edited)
Did you try putting {as:'patient'} in the include statement?
include: [{
model: Patient,
as:'patient',
attributes: ['id']
}]
I have a case when my data in in nested arrays of jsonb in order to find the value I have to do multiple JSONB_ARRAY_ELEMENTS which is costly and takes a lots of nested code.
The json file has the continents inside countries and inside cities.
I need to access a city value.
Is there a way to make this query simpler and faster?
I was trying to solve it using JSON_EXTRACT_PATH but in order to get in to a array but I need the indexes.
WITH mydata AS (
SELECT '
{
"continents":[
{
"name":"America",
"area":43316000,
"countries":[
{
"country_name":"Canada",
"capital":"Toronto",
"cities":[
{
"city_name":"Ontario",
"population":2393933
},
{
"city_name":"Quebec",
"population":12332
}
]
},
{
"country_name":"Brazil",
"capital":"Brasilia",
"cities":[
{
"city_name":"Sao Paolo",
"population":34534534
},
{
"city_name":"Rio",
"population":445345
}
]
}
]
},
{
"name":"Europa",
"area":10530751,
"countries":[
{
"country_name":"Switzerland",
"capital":"Zurich",
"cities":[
{
"city_name":"Ginebra",
"population":4564565
},
{
"city_name":"Basilea",
"population":4564533
}
]
},
{
"country_name":"Norway",
"capital":"Oslo",
"cities":[
{
"city_name":"Oslo",
"population":3243534
},
{
"city_name":"Steinkjer",
"population":4565465
}
]
}
]
}
]
}
'::JSONB AS data_column
)
SELECT cit.city->>'city_name' AS city,
(cit.city->>'population')::INTEGER AS population
FROM (SELECT JSONB_ARRAY_ELEMENTS(coun.country->'cities') AS city
FROM (SELECT JSONB_ARRAY_ELEMENTS(cont.continent->'countries') AS country
FROM (SELECT JSONB_ARRAY_ELEMENTS(data_column->'continents') AS continent
FROM mydata
) AS cont
WHERE cont.continent #> '{"name":"Europa"}'
) AS coun
WHERE coun.country #> '{"country_name" : "Norway"}'
) AS cit
WHERE cit.city #> '{"city_name": "Oslo"}'
See my nested queries? looks ugly, I can get the answer using: JSONB_EXTRACT_PATH( data_column->'continents', '1', 'countries', '1', 'cities', '0', 'population') but I had to hardcode the array indexes.
Hope you can help me out.
Thanks.
You don't need any nesting, you can do lateral queries:
SELECT
city->>'city_name' AS city,
(city->>'population')::INTEGER AS population
FROM
mydata,
JSONB_ARRAY_ELEMENTS(data_column->'continents') AS continent,
JSONB_ARRAY_ELEMENTS(continent->'countries') AS country,
JSONB_ARRAY_ELEMENTS(country->'cities') AS city
WHERE continent ->> 'name' = 'Europa'
AND country ->> 'country_name' = 'Norway'
AND city ->> 'city_name' = 'Oslo';
(online demo)
However, since you mentioned paths and having to specify indices in there, this is actually the perfect use case for Postgres 12 JSON paths:
SELECT jsonb_path_query(data_column, '$.continents[*]?(#.name == "Europa").countries[*]?(#.country_name=="Norway").cities[*]?(#.city_name=="Oslo")') FROM mydata
(online demo)
here, This Query is Perfectly Run in Mysql.
but Overwrite this Query into Laravel(Mongodb) Query Format
SELECT F.status, U.username, U.email
FROM users U, friends F
WHERE
CASE
WHEN F.friend_one = '$user_id'
THEN F.friend_two = U.user_id
WHEN F.friend_two= '$user_id'
THEN F.friend_one= U.user_id
END
AND
F.status='1';
this is friend module and get the my all friend list
here is my table look like
{
"_id" :"5a12618b82956d4c0e00002d",
"otheruser" : "598442b58ed7bc0c19000029",
"relation_type" : 2,
"is_friend" : "true",
"user_id" : "59bf784682956df00c00002a"
}
here is my sample query in repository..
public function GetFriendsOfUser($id,$userId)
{
$list = $this->makeModel()
->with('getallfrienduser')
->where('is_friend',"true")
->where('relation_type',2)
->where(function ($query) use ($id,$userId) {
$query->where('user_id', $userId)
->orWhere('otheruser', $id);
})
->get();
}
here sample join in model and join are sapreated
public function getallfrienduser()
{
return $this->hasMany('App\Models\Users','_id','user_id');
}
public function getallfriendother()
{
return $this->hasMany('App\Models\Users','_id','otheruser');
}
but only one join use(user_id,otheruser) alternatively record find two user.
Can someone explain me why this mdx query executed against Saiku rest api does not return expected cellset? This query is executed as mdx type ThinQuery.
SELECT
{
[Location.CountryHierarchy].[Croatia]
,[Location.CountryHierarchy].[Serbia]
} ON COLUMNS
,Hierarchize
(
Union
(
{
[Product.ProductHierarchy].[Drinks]
,[Product.ProductHierarchy].[Food]
}
,[Product.ProductHierarchy].[Drinks].Children
)
) ON ROWS
FROM [Sales cube];
Expected output(tested with jpivot, pivot4j and Pentaho SchemaWorkbench/MDX explorer)
ExpectedResult
Actual result rendered on Android OLAP client am working on - just to be sure I also checked returned json from saiku server and really cells are missing.
Actual result
If you are executing using the execute endpoint and passing MDX or a Query Model in, you need to play with the properties section, try this:
"properties": {
"saiku.olap.query.automatic_execution": true,
"saiku.olap.query.nonempty": true,
"saiku.olap.query.nonempty.rows": true,
"saiku.olap.query.nonempty.columns": true,
"saiku.ui.render.mode": "table",
"saiku.olap.query.filter": true,
"saiku.olap.result.formatter": "flat",
"org.saiku.query.explain": true,
"org.saiku.connection.scenario": false,
"saiku.olap.query.drillthrough": true
}
Maybe try adding in the [ALL] member for Food to force the issue?
This was my AdvWrks mock-up:
SELECT
{
[Product].[Category].&[4]
,[Product].[Category].&[1]
} ON 0
,Hierarchize
(
Union
(
{
[Customer].[Customer Geography].[Country].&[Australia]
,[Customer].[Customer Geography].[Country].&[Canada]
}
,{
[Customer].[Customer Geography].[Country].&[Australia].Children
,[Customer].[Customer Geography].[Country].&[Canada].[All]
}
)
) ON 1
FROM [Adventure Works]
WHERE
[Measures].[Internet Sales Amount];
So in your scenario:
SELECT
{
[Location.CountryHierarchy].[Croatia]
,[Location.CountryHierarchy].[Serbia]
} ON COLUMNS
,Hierarchize
(
{
[Product.ProductHierarchy].[Drinks]
,[Product.ProductHierarchy].[Food]
,[Product.ProductHierarchy].[Drinks].Children
}
) ON ROWS
FROM [Sales cube];
I am using Mongoose to fetch data from MongoDB. Here is my model.
var EmployeeSchema = new Schema({
name: String,
viewCount: { type: Number, default: 0 },
description: {
type: String,
default: 'No description'
},
departments: []
});
I need to find top 5 employees where count(viewCount) is highest order by name.
I am thinking of finding all the employee by using find() & then read viewCount property & produce the result. is there any better way to get the desired result.
All you need here is .sort() and .limit():
Employee.find().sort({ "viewCount": -1, "name": 1 }).limit(5)
.exec(function(err,results) {
});
And that is the top 5 employees in views ordered by name after the viewCount.
If you want them ordered by "name" in your final five, then just sort that result:
Employee.find().sort({ "viewCount": -1, "name": 1 }).limit(5)
.exec(function(err,results) {
// sort it by name
results.sort(function(a,b) {
return a.name.localeCompare(b.name);
});
// do something with results
});
You can sort by the view count and limit the search results to 5.
In code it might look like this:
Employee
.find()
.sort([['viewCount',-1], ['name',-1]])
.limit(5)
.exec(function(err, results){
//do something with the results here
});