I'm using node-postgres to return a joined table to the front end of my React app through an express server. Here is the query...
SELECT channels.name as channels, programmes.title as title, series.number as series, episodes.episode_number as episode
FROM programmes
INNER JOIN programme_channels ON programme_channels.programme_id = programmes.programme_id
INNER JOIN channels ON programme_channels.channel_id = channels.channel_id
INNER JOIN series ON programmes.programme_id = series.programme_id
INNER JOIN episodes ON series.series_id = episodes.series_id
This works as needed, however I'd like for front-end users to be able to update or delete columns of the table. To do this, each cell of my table would need to know the origin of its data. Currently the query I have returns a table like this...
channel | title | series | episode
--------------+------------+---------------+---------
Some Channel | Some title | 1 | 1
Where channel is from the channels, title, series and episode are all from different tables. For a user to update or delete this data, they will need the origins of each column for the query.
The node-postgres query returns some more information which may be helpful for this in the form of a fields array...
fields: [
Field {
name: 'title',
tableID: 16554,
columnID: 2,
dataTypeID: 1043,
dataTypeSize: -1,
dataTypeModifier: 104,
format: 'text'
},
...]
and I can return a table with the original table name of a column using this query...
SELECT relname
FROM pg_catalog.pg_statio_user_tables
WHERE relid = '16554'
result...
relname
----------
programmes
however I'm not sure how to use the results of this to query the table 'programmes'. This is where I've hit a wall. My questions are...
Am I going about this the right way, or is there an easier way to update data returned from a joined table?
If so, is there any way I can SELECT a table by either the relid or the result of a query.
Related
I want to query a database, get ALL of the user's data, and send it to my front end in a JSON object (with many layers of nesting).
e.g.
{
user_id: 1,
username: james,
messages: [
{
message_id: 'fewfef',
message: 'lorum ipsum'
... : {
...
}
}
]
}
Sample schema/data:
--user table (parent)
CREATE TABLE userdata (
user_id integer,
username text
);
INSERT INTO userdata VALUES (1, 'james');
-- messages table (child) connected to user table
CREATE TABLE messages(
message_id integer,
fk_messages_userdata integer,
message text
);
INSERT INTO messages VALUES (1, 1, 'hello');
INSERT INTO messages VALUES (2, 1, 'lorum ipsum');
INSERT INTO messages VALUES (3, 1, 'test123');
-- querying all data at once
SELECT u.username, m.message_id, m.message FROM userdata u
INNER JOIN messages m
ON u.user_id = m.fk_messages_userdata
WHERE u.user_id = '1';
This outputs the data as so:
username|message_id|message |
--------+----------+-----------+
james | 1|hello |
james | 2|lorum ipsum|
james | 3|test123 |
The issue is I have the username is repeated for each message. For larger databases and more layers of nesting this would cause a lot of useless data being queried/sent.
Is it better to do one query to get all of this data and send it to the backend, or make a seperate query for each table, and only get the data I want?
For example I could run these queries:
-- getting only user metadata
SELECT username from userdata WHERE user_id = '1';
-- output
username|
--------+
james |
-- getting only user's messages
SELECT m.message_id, m.message as message_id FROM userdata u
INNER JOIN messages m
ON u.user_id = m.fk_messages_userdata
WHERE u.user_id = '1';
--output
message_id|message_id |
----------+-----------+
1|hello |
2|lorum ipsum|
3|test123 |
This way I get only the data I need, and its a little easier to work with, as it comes to the backed more organized. But is there a disadvantage of running separate queries instead of one big one? Are there any other ways to do this?
Is it better to do one query to get all of this data and send it to the backend, or make a seperate query for each table, and only get the data I want?
It's best to run only one query and get only the data you want. As long as it doesn't get too complicated - which it doesn't IMO:
SELECT to_json(usr)
FROM (
SELECT u.user_id, u.username
, (SELECT json_agg(msg) -- aggregation in correlated subquery
FROM (
SELECT m.message_id, m.message
FROM messages m
WHERE m.fk_messages_userdata = u.user_id
) msg
) AS messages
FROM userdata u
WHERE u.user_id = 1 -- provide user_id here once!
) usr;
fiddle
There are many other ways.
A (LEFT) JOIN LATERAL instead of the correlated subquery. See:
What is the difference between a LATERAL JOIN and a subquery in PostgreSQL?
json_build_object() instead of converting whole rows from subselects. See:
Return multiple columns of the same row as JSON array of objects
LEFT JOIN query with JSON object array aggregate
But this version above should be shortest and fastest.
Related:
What are the pros and cons of performing calculations in sql vs. in your application
Please who can help with this scenario?
I have two tables, both they have a common column ID, and Table 1 has a column Title. Normally I should update the content of this Title column for some ID, but since the table was already in use somewhere else, it wasn't a good idea to change data directly in Table 1.
That's why I created a new table table 2, which hold only the Title that must be changed associated with these ID that must be changed.
Now I am trying to get these updated titles from table 2, when there is a matching ID in table 1, otherwise show only the contents of table 1.
The result should be something like that but without using If statements.
__ID__ Title
| | | |
| | | |
You can use LEFT OUTER JOIN to this new table and COALESCE() function to say "If there is data in the new table, use it, otherwise use the data in the existing table" . Something like:
SELECT t1.id, COALESCE(t2.title, t1.title) as title
FROM t1
LEFT OUTER JOIN t2 ON t1.id = t2.id;
My goal is to create a query, macro or any solution that can do the task described below.
Lets say I have an access 2016 table named "student" with 12 records like this:
And then, lets say I have a second table named "matchme" with 4 records like this:
I need to find a way to
=> first, create a query that returns result of "graduation_date" are equal to Date "1/31/2017" from Table "student" .
=> second, from the result returned from first step, create a query that compare "email" from "student" table with "email" from "matchme" table, and return the [matched] record result.
So the desired result would be:
since the email gary#xxx.com and thomas#xxx.com exist in both tables.
How can I create a query like this?
you can download my access file from here: experiment.accdb
Simple:
select * from student
inner join matchme on student.email = matchme.email
where student.graduation_date = '1/31/2017'
Looking to your data sample you need a join on date and name between the two tables
select * from student
inner join matchme on student.graduation_date = matchme.graduation_date
and student.email = matchme.email
where student.graduation_date = '1/31/2017'
I have two tables, UserInfo (PrimaryKey= UID) and Relationships (PrimaryKey= RID, ForeignKey= UID).
Relationships data example:
| UID | RID |
| 2 | 3 |
| 3 | 4 |
Now, after executing an sql query, that performs some sorting on Relationships table like:
"select RID from Relationships where UID= "value"
UNION select UID from Relationships where RID= "value "
if the value = 3, i get the integer values such 2 , 4 (which means 3 has relationships with 2 and 4)
if value = 4, result = 3 (4 only has relationship with 3)
etc these resulting values are PrimaryKey values of the UserInfo table.
What i want to do is to fetch the Information of Users having the UID = 23,25,34 (These values are the result of first SQL query, so the number of values and values changes every time according to the values passed to first SQL query)
and bind it with an asp Gridview.
for this, i think i'll have to execute multiple sql queries like
select * from UserInfo where UID= 2
select * from UserInfo where UID= 4
etc
using a loop.
What i think i should do is to loop through the results of first sql query, execute the second query according to it and save the resulting recordset in another table or any sort of datasource, which is finally bind to the gridview... but i don't know how to implement it..
this is my first question in StackOverflow.. i'll try my best to further clarrify the problem if necessory..
any help would be greatly appreciatable..! :)
You can use a SQL join
select a.RID from Friendships a inner join Relationships b on a.uid=b.uid
where a.UID= "value" & b.RID="value"
order by a.uid
This will give you all records which exist in both tables A & B.More on SQL Joins
There is no need to loop as you can execute the query in a single SQL statement like
select * from UserInfo where UID IN (23, 25, 34);
On a short note, select * from table is usually a bad practise & you might want to replace it with your column names
I want to fetch the a field say excep_point from a transparent table z_accounts for the combination of company_code and account_number. How can I do this in ABAP SQL?
Assume that table structure is
|company_code | account_number | excep_point |
Assuming you have the full primary key...
data: gv_excep_point type zaccounts-excep_point.
select single excep_point
into gv_excep_point
from zaccounts
where company_code = some_company_code
and account_number = some_account_number.
if you don't have the full PK and there could be multiple values for excep_point
data: gt_excep_points type table of zaccounts-excep_point.
select excep_point
into table gt_excep_points
from zaccounts
where company_code = some_company_code
and account_number = some_account_number.
There is at least another variation, but those are 2 I use most often.
For information only. When you selects data into table you can write complex expressions to combine different fields. For example, you have internal table (itab) with two fields "A" and "B". And you are going to select data from DB table (dbtab) wich have 6 columns - "z","x","y","u","v","w". And for example each field is type char2 You aim to cimbine "z","x","y","u" in "A" field of internal table and "v","w" in "B" field. You can write simple code:
select z as A+0(2)
x as A+2(2)
y as A+4(2)
u as A+6(2)
v as B+0(2)
w as B+2(2) FROM dbtab
INTO CORRESPONDING FIELDS OF TABLE itab
WHERE <where condition>.
This simple code makes you job done very simple
In addition to Bryans answer, here is the official online documentation about Open SQL.