I'm having a problem, I explain:
I have a table called Tipo_Base that contains Id, nombre_tipo_base
I have a table called Tipo_Base_Lista that contains Id, id_tipo_base, and lista_id
I have a table called Modelo_unidad that contains Id, nombre_modelo and id_tipo_base
I have a table called Modelo_Lista that contains Id, id_modelo, id_lista
Each id_lista of the table modelo_lista MUST be present in the table tipo_base_lista, then, when I delete a id_lista from the table tipo_base_lista, it must also be deleted from the table modelo_lista.
Try the following:
DELETE Tbl_modelo_lista
FROM
Tbl_modelo_lista
INNER JOIN Tbl_modelo_unidad as MU ON MU.id_modelo = Tbl_modelo_lista.id_modelo
INNER JOIN Tbl_tipo_base_lista as TBL ON TBL.id_tipo_base = MU.id_tipo_base
WHERE
TBL.id_lista <> Tbl_modelo_lista.id_lista
I think the logic you want is more like this:
DELETE ml
FROM Tbl_modelo_lista ml INNER JOIN
Tbl_modelo_unidad mu
ON mu.id_modelo = ml.id_modelo LEFT JOIN
Tbl_tipo_base_lista tbl
ON tbl.id_tipo_base = mu.id_tipo_base AND
tbl.id_lista = ml.id_lista
WHERE tbl.id_lista IS NULL;
Normally, the way to implement this logic is with a cascading delete constraint. In your case, I'm not sure this would work. Cascading triggers are useful when you need to propagate changes from the reference table outwards. They don't keep track of incoming references and delete a record when there are no references.
Related
I have three tables in sql.
transcation_table: id(pk), date_time, sender_wallet(fk), amount_sent, sender_updated_balance, receiver_wallet(fk), amount_received, receiver_updated_balance
wallet_table: id(pk), userid(fk), wallet, currency, balance
user_table: id(pk), uname
all 'id' fields are primary keys
wallet_table.userid is foreign key of user_table.id
transaction_table.sender_wallet is foreign key of wallet_table.id
transaction_table.receiver_wallet is foreign key of wallet_table.id
I am trying to ask the database to give me a new table where any of the records in transaction_table contain a sender_wallet and receiver_wallet for a particular user.
The new returned table should be like:
date_time, sender_uname, amount_sent, sender_updated_balance, receiver_uname, amount_received, receiver_updated_balance
sender_uname and receiver_uname are new columns to be created for the purpose of making a distinction between the sender and receiver username in the newly returned table.
A returned result would be something like:
2023-02-03 09:57:38, marvin381, 40.00, 360.00, hamarni242, 40.00, 440.00
I made some poor attempts at trying to receive the intended result.
I am unable to see how I can pull the uname from the wallet_table effectively twice and join to the new table.
I also am not getting close to creating the new columns 'sender_uname' and 'receiver_uname'.
I have managed to get the inner join to work getting the data but with only one uname, but not the uname twice under 'sender' and 'receiver'.
which is not even working or coming close to the result.
select t.id,
t.date_time,
su.uname as sender_uname,
t.amount_sent,
t.sender_updated_balance,
ru.uname as receiver_uname,
t.amount_received,
t.receiver_updated_balance
from transcation_table t
inner join wallet_table sw on t.sender_wallet = sw.id
inner join wallet_table rw on t.receiver_wallet = rw.id
inner join user_table su on su.id = sw.userid
inner join user_table ru on ru.id = rw.userid
where su.id = x or ru.id = x;
That x would be a parameter (or a constant) written depending on your database which you didn't specify in tags.
PS: You could also join wallet_table and user table once with a CTE but I didn't want to go that route without knowing your database.
Here is a DBFiddle sample
I have Four tables as follows
Review (REV_ID pk , REV_NAME)
Meeting (MEETING_ID pk,MEETING_NAME,REV_ID fk to Review)
Task (TASK_ID pk,TASK_NAME,REV_ID fk to Review)
Answer (ANS_ID pk,ANS_NAME,REV_ID fk to Review)
Now I want to select a particular Review and want to create a table with
Linked meetings
Linked answers
Linked tasks
How shall I proceed with it?
I tried writing join query but I was only able to get data if Rev_ID is present in all tables?
select * from
(SELECT *
FROM meeting
WHERE EXISTS (SELECT *
FROM review WHERE meeting.rev_id
=review.rev_id)
and meeting.rev_id=142),
(SELECT *
FROM answer
WHERE EXISTS (SELECT *
FROM review WHERE answer.rev_id
=rev.rev_id)
and answer.ans_rev_id=142),
(SELECT *
FROM task
WHERE EXISTS (SELECT *
FROM review WHERE task.rev_id
=review.rev_id)
and task.rev_id=142) r;
Note : Here I tried static Rev_ID =142 to check data.
From above query i am getting output only if data exist in all four table, But if Data does not exist in any table, It does not return remaining value.
I want at-least names of all table's in final output.
Try the following, let us know if this meets your requirements.
SELECT rv.rev_id,
rv.rev_name,
mt.meeting_name,
tk.task_name,
ans.ans_name
FROM review rv
LEFT OUTER JOIN meeting mt ON (rv.rev_id = mt.rev_id)
LEFT OUTER JOIN task tk ON (rv.rev_id = tk.rev_id)
LEFT OUTER JOIN answer ans ON (rv.rev_id = ans.rev_id)
WHERE rv.rev_id = 142
SQL Fiddle Demo
If the above SQL is fine, prefix it with create table or view syntax to combine them into one.
I have a table I need to update the price field in. I need to update this field from a different price field from a different table. The only way I can get to the required table for the update is by joining another table into this query.
So in all I need to join 3 tables in the update.
Table A has the price field that needs to be updated. In this table I have the foreign key of the product.
Table A structure
-PK_TABLE_A,
-FK_TABLE_B,
-ITEM_COST,
-ITEM_PRICE (needs to be updated from Table C)
Table B is the product table which has the PK of the product. This table is used to access Table C.
I also need to filter Table B to only update a certain stock type.
Table B structure
-PK_TABLE_B,
-FK_TABLE_C,
-DESCRIPTION,
-QUANTITY,
-ITEM_TYPE (a string that needs to be added in where clause to only update records with certain type).
Table C has a foreign key back to Table B. It also contains the price field that I need to use to update the price field in table A
Table C structure
-PK_TABLE_C,
-FK_TABLE_B,
-PRICE (this is the field that I need to use to update the price field in table A)
-USED_DATE,
-ID
The DBMS I am using is Firebird.
I have tried to use sub queries to no avail. I regularly use a sub-select when using two tables to update, so something like
UPDATE table1 AS t1
SET t1.FK = (select table2.PK
FROM table2 INNER JOIN
table1
ON table2.FK = table2.PK
WHERE table2.name = t1.name)
I'm just struggling to use the same technique with a 3rd table incorporated.
I am not even sure if this is the correct way to go about this situation. I have looked on google, but most examples I have come across don't utilise the 3rd table.
Any help would be appreciated.
**edited to included more detail on table structure.
are you able to show us the table structures in more detail?
if both tableA and tableC have a foreign key that points back to tableB I don't think you need to include a three table join. you just need to
update tableA set ITEM_PRICE = SELECT(PRICE FROM TableC WHERE
TableA.FK_TABLE_B = TableC.FK_TABLE_B;
unless I'm missing something?
edited to reflect a better understanding of the problem
alright, I think I've got it this time:
update tableA set price =
(select price from tableC where tableA.fk_tableB = tableC.fk_tableB) where
(Select item_type from tableB where tableB.pk_tableB = tableA.fk_tableB) =
'$itemTypeVariable';
edited again with a better understanding of the problem
There are five tables
Items (ItemNo,productName)
ProductBatch (productBatchId,ItemNo,batchName,purchaseRate)
DamageStock (AdjustmentId,date,description)
DamageStockItem (damageStockDetailsId,AdjustmentId,productBatchId)
StockPosting (serialNumber,productBatchId,outwardQuantity,voucherType).
My aim is that to retrieve all information from above tables for each damage stock item through this query:
select
P1.ItemNo, B1.productBatchId, S1.serialNumber,
P1.productName, S1.outwardQuantity, DS.damageStockDetailsId
FROM
Items AS P1
INNER JOIN
ProductBatch AS B1 ON P1.ItemNo = B1.ItemNo
INNER JOIN
StockPosting AS S1 ON B1.productBatchId = S1.productBatchId
INNER JOIN
DamageStockItem as DS on DS.productBatchId = B1.productBatchId
INNER JOIN
DamageStock AS MASTER1 ON MASTER1 .AdjustmentId = DS.ItemAdjustmentId
WHERE
S1.voucherType = 'Damage Stock'
AND DS.ItemAdjustmentId = '10001'
but it shows duplicate values for damageStockDetailsId which is the primary key of DamageStockItem table and I don't know that there is any problem in the relationships between these tables or no and also I solved this problem when I made a relation between StockPosting table and DamageStock , I put the primary key of StockPosting table in DamageStockItem as foreign key and it did not show any duplicate value. I want to know that this relationship is correct or no. I need your ideas regarding this issue.
You can have several damageStockDetailsId per AdjustmentId in your table DamageStockItem (or DamageStockDetails, whatever it is called).
As those are connected to an AdjustmentId you should output that too, to see where the (seemingly same) damageStockDetailsIds belong to.
I have three denormalized tables that I have to take at face value (data comes from some external resource). The three tables have different definitions, but they each describe the same object from different perspectives.
object1 A B
object2 A
object3 B C
object4 C
The only commonality between these tables is their primary key. I can corral the IDs together using SELECT UNION SELECT, but the query seems relatively slow, even when each table has its PK field indexed. I could create a view to abstract this query, vw_object_ids, but it performs at the same speed. I thought I could add an index to materialize the view, but in SQL Server 2005, you can't index views with UNIONs.
What I want is to have a master index of IDs be in sync with with the underlying data, which may get updated or deleted whenever. I guess I could accomplish this indefinitely with a crazy set of triggers or just settle for the speed of the unindexed view. But I just wanted to make sure I'm not missing any options or if this scenario has a name or is indicative of a pattern.
Thoughts?
Create a master table that contains only the ID:
CREATE TABLE master (ID INT NOT NULL PRIMARY KEY)
and make all three tables to refer to that master table with ON DELETE CASCADE.
To populate the table for the first time, issue
INSERT
INTO master
SELECT id
FROM a
UNION
SELECT id
FROM b
UNION
SELECT id
FROM c
To populate the table on a regular basis, create a trigger on each of three tables.
This trigger should try to insert the new ID to master and silently fail on PRIMARY KEY violation.
To query, use:
SELECT *
FROM master m
LEFT OUTER JOIN
a
ON a.id = m.id
LEFT OUTER JOIN
b
ON b.id = m.id
LEFT OUTER JOIN
c
ON c.id = m.id
This will use indexes efficienty.
To delete, use:
DELETE
FROM master
WHERE id = #id
This will fire ON DELETE CASCADE and delete records from all three tables if any.
Why not just do an outer join and then coalesce the columns from the component tables?