Delete a record from a table referring to 2 or more columns from another table - sql

Consider having 2 tables as follows.
Table 1:
Unit
SKU number
Active
A
1
Y
B
2
Y
c
3
Y
Table 2:
Unit
SKU number
description
X
4
Apple
B
2
Mango
Y
5
Grapes
z
6
Banana
I wanted to delete record B,2,Y from table 1 by referring to table 2 where values in columns Unit and SKU number match.
I tried using the following query but it didn't seem to work
DELETE FROM table1
WHERE (Unit, SKU_Number) IN (SELECT Unit, SKU_Number FROM table2);
The error was
An expression of non-boolean type specified in a context where a condition is expected, near ','
Can someone please help me understand what I am doing wrong here or help me rewrite the SQL query to achieve the required objective?

You could use similar logic with exists:
DELETE
FROM table1 t1
WHERE EXISTS (SELECT 1 FROM table2 t2
WHERE t2.Unit = t1.Unit AND t2.SKU_Number = t1.SKU_Number);

You can try using this query, assuming Unit of Table 1 is unique:
DELETE FROM table1
WHERE table1.Unit IN (
SELECT table1.Unit
FROM table1
LEFT JOIN table2 ON table1.Unit = table2.Unit
AND table1.SKU_Number = table2.SKU_Number
)
If unit is not an unique field, simply replace it with whichever field is unique, or with primary key of Table 1.

You can use inner join for delete:
DELETE t1
FROM table1 t1
INNER JOIN table2 t2
ON t1.unit=t2.unit and t1.SKU_Number = t2.SKU.Number

Related

SQL insert into table with values selected from other tables where an external value matches

I have the following tables:
Table1:
id
rarity
1
Common
2
Uncommon
3
Rare
Table2:
id
Type
1
Air
2
Earth
3
Fire
4
Water
The output table already exists and the schema is the following:
rarityID
weakness_typeID
resistance_typeID
and I should fill it with rows according to the Table2 and Table1.
For example if I'm given:
type is 'Water' and 'Air'
rarity is 'Common'
I'd like to add the IDs contained in Table1 and Table2 to this table to get the following updated output table:
rarityID
weakness_typeID
resistance_typeID
1
4
1
I've written the following query:
INSERT INTO table3 (rarityID, weakness_typeID, resistance_typeID)
SELECT rar.id, weak.id, res.id
FROM table1 rar, table2 weak, table2 res
WHERE rar.rarity = `Common`
AND weak.type = `Water`
AND res.type = `Air`;
But it doesn't work, can you help me?
My understanding of your problem is that you're trying to get ids for each of your information.
If this is correct, in order to do this you need to select their ids in three separate queries like it is done in the following query:
INSERT INTO table3 (rarityID, weakness_typeID, resistance_typeID)
SELECT (SELECT rar.id
FROM table1 rar
WHERE rar.rarity = 'Common') AS rarityID,
(SELECT weak.id
FROM table2 weak
WHERE weak.type = 'Water') AS weakness_typeID,
(SELECT weak.id
FROM table2 weak
WHERE weak.type = 'Air') AS resistance_typeID;
If you want to play with this code, check this SQL Fiddle.

How to delete rows from two tables which are in common with single query in postgresql

I have two tables t1 and t2
table t1 as follows:
id name
1 x
2 y
3 z
table t2 as follows:
id name
1 a
121 b
131 c
Here I am selecting rows that are common in both the tables i.e.,
SELECT *
from t1,t2
where t1.id=t2.id;
Now I want to delete the rows when id=1 in both the tables at once. I have tried to delete the rows but I am able to delete only in one table but not both. Can anyone help me out in solving this.
You can do that with a data modifying common table expression
with common_ids as (
select id
from t1
intersect
select id
from t2
), t1_delete as (
delete from t1
where id in (select id from common_ids)
)
delete from t2
where id in (select id from common_ids);
Online example: http://rextester.com/NAQ26877

add new column with matching id in both Table 1 and Table 2

I have two tables,
in table1 I have 5 rows and
in table2 3 rows
table1:
#no---Name---value
1-----John---100
2-----Cooper-200
3-----Mil----300
4-----Key----200
5-----Van----300
Table 2:
#MemID-#no---FavID
19-----1-----2
21-----1-----3
22-----2-----5
Now expected result:
#no---name---value---MyFav
1-----John---100-----NULL
2-----Cooper-200-----1
3-----Mil----300-----1
4-----Key----200-----NULL
5-----Van----300-----NULL
1 indicates - My favorites
MyFav - new column ( alias)
This is the expected result, please suggest how to get it.
I think I understand the logic. You want MyFav to be marked as a 1 if that row is a favorite of John. You can do this with a left join and some more filtering:
select t1.*,
(case when t2.#no is not null then 1 end) as MyFav
from table1 t1 left join
table2 t2
on t1.#no = t2.FavId and
t2.#no = (select tt1.#no from table1 tt1 where tt1.Name = 'John');
Just use natural join for that, It will use your primary key as a mediator to join both the tables, as required. In your case, I think primary key is #no
For more information on natural join please visit SQL Joins

How to write a query to get only first matching row while joining two tables?

Consider I have following tables:
Table 1:
AId
AMoniker
Table2:
BId
BMoniker
Table1->Table2 is one to many relationship
I want a temp table out of these two tables where if a particular Amoniker has multiple BMonikers then only first one should go in the table.
For example, if tables have following data:
Table1:
1 ABCD
2 DEFG
3 QWER
Table 2:
1 QZ
1 XC
1 CV
2 DE
2 OP
3 QW
the query should return the following:
ABCD QZ
DEFG DE
QWER QW
My query to get all the rows is:
select b.BMoniker, a.AMoniker
into #moniker_map
from Table1 a inner join Table2 b
on a.Aid=b.Bid
How can i modify this to get only 1st row from Table2 for each Id.
I tried following query:
select b.BMoniker, a.AMoniker
from Table1 a inner join Table2 b
on a.Aid=b.Bid
and b.BMoniker in
(
select top 1 BMoniker
from Table2
where Bid=cb.Bid
ORDER BY BMoniker
)
But i get following error:
Incorrect syntax near keyword 'top'
Sybase error code = 156, SQLState="ZZZZZ"
Selects row with minimum value from table2 (PostgreSQL syntax):
SELECT a.AMoniker, MIN(b.BMoniker) FROM Table1 a, Table2 b
WHERE a.Aid = b.Bid GROUP BY 1;
Maybe it is a typo but it looks like your subquery is referencing an table alias cb which is not defined. Can you try this:
select b.BMoniker, a.AMoniker
from Table1 a inner join Table2 b
on a.Aid=b.Bid
and b.BMoniker in
(
select top 1 BMoniker
from Table2 c
where c.Bid=a.Bid
ORDER BY BMoniker
)

How do I Write a SQL Query With a Condition Involving a Second Table?

Table1
...
LogEntryID *PrimaryKey*
Value
ThresholdID - - - Link to the appropriate threshold being applied to this log entry.
...
Table2
...
ThresholdID *PrimaryKey*
Threshold
...
All fields are integers.
The "..." thingies are there to show that these tables hold a lot more imformation than just this. They are set up this way for a reason, and I can't change it at this point.
I need write a SQL statement to select every record from Table1 where the Value field in that particular log record is less than the Threshold field in the linked record of Table2.
I'm newish to SQL, so I know this is a basic question.
If anyone can show me how this SQL statement would be structured, it would be greatly appreciated.
SELECT T1.*
FROM Table1 T1
JOIN Table2 T2 ON T2.ThresholdID = T1.ThresholdID
WHERE T2.Threshold > T1.Value
SELECT t1.*
FROM dbo.Table1 t1 INNER JOIN dbo.Table2 t2 ON t1.ThresholdID = t2.ThresholdID
WHERE t2.Threshold > t1.Value
SELECT * from table1 t1 join table2 t2 on (t1.thresholdId = t2.thresholdId)
where t1.value < t2.threshold;
SELECT t1.LogEntryID, t1.Value, t1.ThresholdID
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.ThresholdID = t2.ThresholdID
WHERE t1.Value < t2.threshold
SELECT * FROM Table1
JOIN Table2
ON table1.ThresholdID = table2.ThresholdID --(assuming table 2 holds the same value to link them together)
WHERE
value < thresholdvalue
A 'JOIN' connects 2 tables based on the 'ON' clause (which can be multipart, using 'AND' and 'OR')
If you have 3 entries in table 2 which share table1's primary key (a one-to-many association) you will receive 3 rows in your result set.
for the tables below, for example:
Table 1:
Key Value
1 Hi
2 Bye
Table 2:
Table1Key 2nd_word
1 You
1 fellow
1 friend
2 now
this query:
SELECT * FROM Table1
JOIN Table2
on table1.key = table2.table1key
gets this result set:
Key Value Table1Key 2nd_word
1 Hi 1 You
1 Hi 1 fellow
1 Hi 1 friend
2 Bye 2 now
Note that JOIN will only return results when there is a match in the 2nd table, it will not return a result if there is no match. You can LEFT JOIN for that (all fields from the second table will be NULL).
JOINs can also be strung together, the result from the previous JOIN is used in place of the original table.