SQL - Update table changing one column value based on another table - sql

Sorry if the title is not as descriptive as it should be but it is kind of difficult to explain in one sentence what I am trying to do ;).
I have one table that links parent objects with its respective childs. And I have another table with all the objects (parents and childs) with its respectives images. However, the image is just set for the parents objects. I would like to update this last table and set the childs image the same image that is already set for its parent. Besides, as there is more than one image for each object, I would like to set one in particular, which I can know based on an attribute column.
My tables look something like:
RelationTable
child-id
parent-id
ImageTable
object-id
attribute-id
image-url
And here goes an example in order to clarify things:
RelationsTable
child-id | parent-id
3 | 1
4 | 1
5 | 2
ImageTable
object-id | attribute-id | image-url
1 | goodimage | image1.jpg
1 | badimage | image1b.jpg
2 | goodimage | image2.jpg
2 | badimage | image2b.jpg
3 | goodimage | no
3 | badimage | no
4 | goodimage | no
4 | badimage | no
5 | goodimage | no
5 | badimage | no
So, I would like to set the images of objects 3, 4 and 5 (child ones) to its respective parent images, but to the 'correct' ones, that is the images with 'goodimage' as attribute-id.
At the end it should look like:
1 | goodimage | image1.jpg
1 | badimage | image1b.jpg
2 | goodimage | image2.jpg
2 | badimage | image2b.jpg
3 | goodimage | image1.jpg
3 | badimage | no
4 | goodimage | image1.jpg
4 | badimage | no
5 | goodimage | image2.jpg
5 | badimage | no
Actually, I don't care if 'badimage' is set as well, but the important one is 'goodimage'.
I've been trying something like:
UPDATE ImageTable
SET image = (SELECT image-url FROM ImageTable WHERE ImageTable.object-id = RelationTable.parent-id AND ImageTable.attribute-id = 'goodimage')
WHERE ImageTable.object-id = RelationTable.child-id AND ImageTable.attribute-id = 'goodimage'
but it's not working since it is not correct SQL syntax. I don't know if I should use a variable (never used one) or if this can be done with just one SQL sentence.
Any help would be much appreciated.

something like this?
NOTES:
This could be merged into one
non-subquery statement but I was
lazy.
I did not test, expect typos
;WITH goodlist AS
(
SELECT child-id, image-url
FROM relationstable
left join imagetable on relationstable.child-id = relationstable.child-id and attribute-id = "goodimage"
)
UPATE imagetable
set imagetable.image-url =
(SELECT top 1 image-url from goodlist where child-id = imagetable.object-id)
WHERE imagetable.image-url = "no"

First of all, if the relation between parent and child is 1:n, why don't you just add that information to the same table? e.g. fieldname "parentid" (if it's empty/null it's only a parent). Benefit: you don't need an additional table and can easily create a hierarchy if needed.
And for the image, I guess you want to display this somewhere in your code, but it should be easier to just modify the SELECT to get the image-url of the parent is no image is given for the child. Benefit: no need to update the table when you get new entries and it would also be possible to for some child entries to have their own image (if needed).
edit: just noticed your new comment about the open-source project part, of course this makes it hard to change the database design. But maybe it's still easier to move some of the problems to the programming side (unless this is handled by the open-source software as well).

Related

how to have one itempointer serialize from 1 to n across the selected rows

as shown in the example below, the output of the query contains blockid startds from 324 and it ends at 127, hence, the itempointer or the row index within the block starts from one for each new block id. in otherwords, as shown below
for the blockid 324 it has only itempointer with index 10
for the blockid 325 it has itempointers starts with 1 and ends with 9
i want to have a single blockid so that the itempointer or the row index starts from 1 and ends with 25
plese let me know how to achive that and
why i have three different blockids?
ex-1
query:
select ctid
from awanti_grid_cell_data agcd
where selectedsiteid = '202230060950'
and centerPointsOfWindowAsGeoJSONInEPSG4326ForCellsInTreatment IS NOT NULL
and centerPointsOfWindowAsGeoJSONInEPSG4326ForCellsInTreatment <> 'None'
result:
|ctid |
|--------|
|(324,10)|
|(325,1) |
|(325,2) |
|(325,3) |
|(325,4) |
|(325,5) |
|(325,6) |
|(325,7) |
|(325,8) |
|(325,9) |
|(326,1) |
|(326,2) |
|(326,3) |
|(326,4) |
|(326,5) |
|(326,6) |
|(326,7) |
|(326,8) |
|(326,9) |
|(327,1) |
|(327,2) |
|(327,3) |
|(327,4) |
|(327,5) |
|(327,6) |
You are missing the point. The ctid is the physical address of a row in the table, and it is none of your business. The database is free to choose whatever place it thinks fit for a table row. As a comparison, you cannot go to the authorities and request that your social security number should be 12345678 - it is simply assigned to you, and you have no say. That's how it is with the physical location of tuples.
Very likely you are not asking this question out of pure curiosity, but because you want to solve some problem. You should instead ask a question about your real problem, and there may be a good answer to that. But whatever problem you are trying to solve, using the ctid is probably not the correct answer, in particular if you want to control it.

Database Table: Quantity or redundancy

I'm building a database which have a lot of items for a bike shop. This bike shop have many of the same items such as 100 wheels of size 4 and color 'red'. My question is:
Is is better to add a 'Quantity' field to the entity set and put all similar items in one entity (example 1) or is it better to have an entity for each item (example 2)?
Example 1:
id | color | size | quantity
1 | red | 4 | 100
Example 2:
id | color | size
1 | red | 4
2 | red | 4
3 | red | 4
etc.
The first - qqhantity field - unless you have a reason to track for example serial numbers, and even then you may go to v1 and use a separate column.
Generally: get a copy of the Data Model Ressoure Book Vol 1 - it has a ton of discussions about standard business data problems, among them an inventory system. You will learn a lot.

parse multiline varchar field into rows (T-sql)

I am making a report in SSRS. Database contains table "Project" with a "Notes" field which is formated by users in this way:
#Completed
-line 1 description
-line 2 description
-line3 and so on
#Planned
-line 1 etc.
#Risks
- line1 ...etc
There are always only those 3 categories and in that order. Bullet points can be from 0 to unlimited (but i never seen more than 10)
I would like to get output(dataset) in format (so I can group them in tablix):
ProjectID, Maincategory, itemID, subcategories.
For example
1 | Completed | 1 | line1
1 | Completed | 2 | line2
1 | Completed | 3 | line3
...
1 | Planned | 1 | Line1
...
1 | Risks | 1 | line1
...
I cant change source DB so I cant create stored procedure, it should be regular query.
I looked at various solutions with CTE recursions but I just cant figure out how they work in oreder to change them for my case.
Thank you!

Creating a flattened table/view of a hierarchically-defined set of data

I have a table containing hierarchical data. There are currently ~8 levels in this hierarchy.
I really like the way the data is structured, but performance is dismal when I need to know if a record at level 8 is a child of a record at level 1.
I have PL/SQL stored functions which do these lookups for me, each having a select * from tbl start with ... connect by... statement. This works fine when I'm querying a handful of records, but I'm in a situation now where I need to query ~10k records at once and for each of them run this function. It's taking 2-3 minutes where I need it to run in just a few seconds.
Using some heuristics based on my knowledge of the current data, I can get rid of the lookup function and just do childrecord.key || '%' LIKE parentrecord.key but that's a really dirty hack and will not always work.
So now I'm thinking that for this hierarchically-defined table I need to have a separate parent-child table, which will contain every relationship...for a hierarchy going from level 1-8 there would be 8! records, associating 1 with 2, 1 with 3,...,1 with 8 and 2 with 3, 2 with 4,...,2 with 8. And so forth.
My thought is that I would need to have an insert trigger where it will basically run the connect by query and for every match going up the hierarchy it will insert a record in the lookup table. And to deal with old data I'll just set up foreign keys to the main table with cascading deletes.
Are there better options than this? Am I missing another way that I could determine these distant ancestor/descendant relationships more quickly?
EDIT: This appears to be exactly what I'm thinking about: http://evolt.org/working_with_hierarchical_data_in_sql_using_ancestor_tables
So what you want is to materialize the transitive closures. That is, given this application table ...
ID | PARENT_ID
------+----------
1 |
2 | 1
3 | 2
4 | 2
5 | 4
... the graph table would look like this:
PARENT_ID | CHILD_ID
-----------+----------
1 | 2
1 | 3
1 | 4
1 | 5
2 | 3
2 | 4
2 | 5
4 | 5
It is possible to maintain a table like this in Oracle, although you will need to roll your own framework for it. The question is whether it is worth the overhead. If the source table is volatile then keeping the graph data fresh may cost more cycles than you will save on the queries. Only you know your data's profile.
I don't think you can maintain such a graph table with CONNECT BY queries and cascading foreign keys. Too much indirect activity, too hard to get right. Also a materialized view is out, because we cannot write a SQL query which will zap the 1->5 record when we delete the source record for ID=4.
So what I suggest you read a paper called Maintaining Transitive Closure of Graphs in SQL by Dong, Libkin, Su and Wong. This contains a lot of theory and some gnarly (Oracle) SQL but it will give you the grounding to build the PL/SQL you need to maintain a graph table.
"can you expand on the part about it
being too difficult to maintain with
CONNECT BY/cascading FKs? If I control
access to the table and all
inserts/updates/deletes take place via
stored procedures, what kinds of
scenarios are there where this would
break down?"
Consider the record 1->5 which is a short-circuit of 1->2->4->5. Now what happens if, as I said before, we delete the the source record for ID=4? Cascading foreign keys could delete the entries for 2->4 and 4->5. But that leaves 1->5 (and indeed 2->5) in the graph table although they no longer represent a valid edge in the graph.
What might work (I think, I haven't done it) would be to use an additional synthetic key in the source table, like this.
ID | PARENT_ID | NEW_KEY
------+-----------+---------
1 | | AAA
2 | 1 | BBB
3 | 2 | CCC
4 | 2 | DDD
5 | 4 | EEE
Now the graph table would look like this:
PARENT_ID | CHILD_ID | NEW_KEY
-----------+----------+---------
1 | 2 | BBB
1 | 3 | CCC
1 | 4 | DDD
1 | 5 | DDD
2 | 3 | CCC
2 | 4 | DDD
2 | 5 | DDD
4 | 5 | DDD
So the graph table has a foreign key referencing the relationship in the source table which generated it, rather than linking to the ID. Then deleting the record for ID=4 would cascade deletes of all records in the graph table where NEW_KEY=DDD.
This would work if any given ID can only have zero or one parent IDs. But it won't work if it is permissible for this to happen:
ID | PARENT_ID
------+----------
5 | 2
5 | 4
In other words the edge 1->5 represents both 1->2->4->5 and 1->2->5. So, what might work depends on the complexity of your data.

How to represent and insert into an ordered list in SQL?

I want to represent the list "hi", "hello", "goodbye", "good day", "howdy" (with that order), in a SQL table:
pk | i | val
------------
1 | 0 | hi
0 | 2 | hello
2 | 3 | goodbye
3 | 4 | good day
5 | 6 | howdy
'pk' is the primary key column. Disregard its values.
'i' is the "index" that defines that order of the values in the 'val' column. It is only used to establish the order and the values are otherwise unimportant.
The problem I'm having is with inserting values into the list while maintaining the order. For example, if I want to insert "hey" and I want it to appear between "hello" and "goodbye", then I have to shift the 'i' values of "goodbye" and "good day" (but preferably not "howdy") to make room for the new entry.
So, is there a standard SQL pattern to do the shift operation, but only shift the elements that are necessary? (Note that a simple "UPDATE table SET i=i+1 WHERE i>=3" doesn't work, because it violates the uniqueness constraint on 'i', and also it updates the "howdy" row unnecessarily.)
Or, is there a better way to represent the ordered list? I suppose you could make 'i' a floating point value and choose values between, but then you have to have a separate rebalancing operation when no such value exists.
Or, is there some standard algorithm for generating string values between arbitrary other strings, if I were to make 'i' a varchar?
Or should I just represent it as a linked list? I was avoiding that because I'd like to also be able to do a SELECT .. ORDER BY to get all the elements in order.
As i read your post, I kept thinking 'linked list'
and at the end, I still think that's the way to go.
If you are using Oracle, and the linked list is a separate table (or even the same table with a self referencing id - which i would avoid) then you can use a CONNECT BY query and the pseudo-column LEVEL to determine sort order.
You can easily achieve this by using a cascading trigger that updates any 'index' entry equal to the new one on the insert/update operation to the index value +1. This will cascade through all rows until the first gap stops the cascade - see the second example in this blog entry for a PostgreSQL implementation.
This approach should work independent of the RDBMS used, provided it offers support for triggers to fire before an update/insert. It basically does what you'd do if you implemented your desired behavior in code (increase all following index values until you encounter a gap), but in a simpler and more effective way.
Alternatively, if you can live with a restriction to SQL Server, check the hierarchyid type. While mainly geared at defining nested hierarchies, you can use it for flat ordering as well. It somewhat resembles your approach using floats, as it allows insertion between two positions by assigning fractional values, thus avoiding the need to update other entries.
If you don't use numbers, but Strings, you may have a table:
pk | i | val
------------
1 | a0 | hi
0 | a2 | hello
2 | a3 | goodbye
3 | b | good day
5 | b1 | howdy
You may insert a4 between a3 and b, a21 between a2 and a3, a1 between a0 and a2 and so on. You would need a clever function, to generate an i for new value v between p and n, and the index can become longer and longer, or you need a big rebalancing from time to time.
Another approach could be, to implement a (double-)linked-list in the table, where you don't save indexes, but links to previous and next, which would mean, that you normally have to update 1-2 elements:
pk | prev | val
------------
1 | 0 | hi
0 | 1 | hello
2 | 0 | goodbye
3 | 2 | good day
5 | 3 | howdy
hey between hello & goodbye:
hey get's pk 6,
pk | prev | val
------------
1 | 0 | hi
0 | 1 | hello
6 | 0 | hi <- ins
2 | 6 | goodbye <- upd
3 | 2 | good day
5 | 3 | howdy
the previous element would be hello with pk=0, and goodbye, which linked to hello by now has to link to hey in future.
But I don't know, if it is possible to find a 'order by' mechanism for many db-implementations.
Since I had a similar problem, here is a very simple solution:
Make your i column floats, but insert integer values for the initial data:
pk | i | val
------------
1 | 0.0 | hi
0 | 2.0 | hello
2 | 3.0 | goodbye
3 | 4.0 | good day
5 | 6.0 | howdy
Then, if you want to insert something in between, just compute a float value in the middle between the two surrounding values:
pk | i | val
------------
1 | 0.0 | hi
0 | 2.0 | hello
2 | 3.0 | goodbye
3 | 4.0 | good day
5 | 6.0 | howdy
6 | 2.5 | hey
This way the number of inserts between the same two values is limited to the resolution of float values but for almost all cases that should be more than sufficient.