Stored Procedure for finding N Level Child List - javascript

Recently i came across one problem of finding N Level Child from tables.
Let say we have following list of tables:
Table: **Country**
PKCountryID
CountryCode
CountryName
Table: **State**
PKStateID
FKCountryID
StateCode
StateName
Table: **Area**
PKAreaID
FKStateID
AreaCode
AreaName
Table: **Customer**
PKCustomerID
FKAreaID
CustomerCode
CustomerName and so on....
Here we need to find a way by which we can get N level Treeview with All Columns
Just Like
>Country
Country Table Column
Foreign Key Column of Country Table(Here : FKStateID)
>State
State Table Column
Foreign Key Column of State Table
and so on till N Level.
Is there any solution?

You can basically create the hierarchy using a CTE. If you build hte CTE properly, it will load as many levels as you need. However, I've built these before and you must be very careful in writing the code and how you write it or else performance may suffer.
Do try to use CTE to grab the information and determine if that will fit your need.

Related

Insert into SQL a List if items postgresql

I have a situation where I need to insert
into multiple tables and the last table will depend on the table before it with some extra list of items. I am using pg with node and javascript.
Table 1:
insert into col1, col2 values (1, 2) return col1 as table1_id
Table 2:
insert into col1 col2 values ( table1_id, val1),
(table1_id, val2),
.
.
.
.
(table1_id, val_n)
I have seen here some who have done that but with just 1 row in the last table but I will have a list of items as val1....valn... to be merged with the id generated from the first insert in table1 and added to a list that I have. This is going to be a relationship table with a list of items that belong to a record in table1.
Any clues would be appreciated..
Thanks
I think you should create a 'dao' layer in postgres. An Postgres function with all parameters and return what you should have in frontend.
And this postgres function insert all row what you want.
Like this you can manage your problem:
CREATE OR REPLACE FUNCTION function_what_i_want(val1 integer, val2 integer, my_argument integer[])
RETURNS my_schema_and_table[] AS
$BODY$
DECLARE
result my_schema_and_table[];
BEGIN
insert into table1(col1,col2,col3) VALUES (nextval('seq1'),val1, val2);
insert into table2(c1,c2)
select currval('seq1'),m.c2
from unnest(my_argument) m(c2);
END;
I don't know your project. If you doesn't want search on this tables, perhaps is better store this lists in json.

how should i store lists of lists in MYSQL

I want to store this list of lists but I don't know how to store it in MySQL
list[x][y] the items in this list contains {li:[{x:x,y:y}] , pos:{x:y}}
list[x][y].li[z].x
list[x][y].li[z].y
list[x][y].pos.x
list[x][y].pos.y
for better undersing, please have a look at this
edited:
is this right? so this means i will only have 2 tables?
You should use a separate table with sub-lists that have a column parent_id, and then a third table with actual list items of low level lists.
The query for this will look like this:
SELECT li.x, li.y, sl.id
FROM li_items li
JOIN sub_lists sl on li.list_id = sl.id
JOIN lists l on sl.parent_id = l.id;
The process of converting the result rows depends on if you use some ORM or plain mysql client.
You could also store it as a JSON, as deleted answer has suggested, but than you wan't be able to query specific items without selecting and parsing all the lists. You could also use MySQL's JSON column, but In your case having separate tables seems to be better

BookshelfJS belongsToMany doesn't return duplicates

I have two tables that are have the relationship belongsToMany. The pivot table also contains a column called state that could have 3 different values. Say my tables are Table1 and Table2.
There can be multiple entries for the same Table1-Table2 relation with different states.
I want to get all the pivot entries for Table1 including any multiple entries for the same Table2.
Unfortunately, the code
return this.belongsToMany(Table2, 'pivot_table1_table2').withPivot(['state'])
only returns the first entry for each Table2.
Help is appreciated.
That's how bookshelf works! It's part of the feature: remove the dupes. I found a workaround; explicitly select an attribute from the junction table that's unique. If you don't have one, create a model for the junction table. That's sadly the only solution then.
UPDATE:
Perhaps something like that. routes.code is unique in my case and it is part of the junction table. If this won't do the trick, create a model for the junction table and you're set (this is probably more preferred).
new Station().where({
id: req.params.id
}).fetch({
withRelated: [{
'routes': function(qb) {
qb.select('routes.id', 'routes.code');
}
}]
}).then(function(result) {
res.json(result.toJSON());
});

One to many Foreign Key relation Sqlite

So right now I'm trying to draw relations between 3 different tables using sqlite I'm relatively new to sqlite but saw that you can draw relations by using foreign keys thus optimizing performance. So right now here is my sql statements creating my tables:
'CREATE TABLE IF NOT EXISTS shifts (
shifts_id primary integer,
shift_base_id integer,
shift_site_id integer)';
'CREATE TABLE IF NOT EXISTS sites (
site_id primary integer,
site_info text,
FOREIGN KEY(site_id) REFERENCES shifts(shift_site_id))';
'CREATE TABLE IF NOT EXISTS bases (
base_id primary integer,
base_info text,
FOREIGN KEY(base_id) REFERENCES shifts(shift_base_id))';
So what I'm trying to do is draw relations between the child tables (sites and bases) with the parent table (shifts) by the id. The problem I'm running into is I'm getting a "foreign key mismatch" error. I read somewhere that in sqlite you can only REFERENCE a primary or unique key within the parent table. The problem with this is that multiple shifts can share the same sites and bases. For instance base_id could equal 1234 and multiple shifts would have shifts_base_id = 1234.
Also there will be times where a base_id in the bases table wont have a matching shift_base_id in the shifts table.
So my question is how to reference this one to many relation between multiple tables? And how to make that relation optional.
You have your relationships backwards. You list the foreign keys in the table that reference the other tables.
CREATE TABLE IF NOT EXISTS shifts (
shifts_id primary integer,
shift_base_id integer,
shift_site_id integer,
FOREIGN KEY (shift_base_id) REFERENCES bases (base_id),
FOREIGN KEY (shift_site_id) REFERENCES site (site_id));

Generating a pivot table from a sql query

I have a project that consist of a function that generate a table based on some filter. Then, I found a problem that when some combination of some filter are return nothing so, when it rendered in browser as a table is less than number of combination.
To achieve it, I want to give "-" mark to the loss record that not saved in the table.
My first approach is check one-by-one the array with the filter and if the condition is match to 'loss rows', it will push array untill all missing record in result is filled with '-'. But, it'll dealing with time because, the last must be sorted again and then to be constructed into the wanted table.
Sample schema of main table "A":
amount_of_product, id_product, id_people, id_place.
The primary key columns are:
id_product, id_people, id_place.
The content of the main table is:
23456, book-a, 1, aa
5678, book-b, 1, cc
2587, book-b, 1, aa
The source query will be something like:
select * from A
where
id_product in ('book-a', 'book-b')
and id_people in ('1') and id_place in ('aa', 'bb', 'cc')
order by id_product, id_place
Then, we want to show in a table view (html) all combinations of all selected filters. 6 rows should be rendered, with empty cells shown as "-".
Sample result table:
Can I do it efficiently or are there any solution to this?
Thanks in advance.
Thanks for some advice above.
I've try to use crosstab function in postgresql to produce the pivot table but I can't produce for more complex table.
So, I use another approach to retrieve all datas based on combination row-coloumn gradually (example query from id_place 'aa', id_people '1', id-product 'aa' etc) and contruct each table head row and coloumn then contruct the data.
Regard

Categories

Resources