select table to select from, dependent on column-value of already given table - sql

for my intention I have to select a table to select columns from dependent on the column-value of an already given table.
First I thought about a CASE construct, if this is possible with sqlite.
SELECT * FROM
CASE IF myTable.column1 = "value1" THEN (SELECT * FROM table1 WHERE ...)
ELSE IF myTable.column1 = "value2" THEN (SELECT * FROM table2 WHERE ...)
END;
I am new to SQL. What construct would be the most concise (not ugly) solution and if I cannot have it in sqlite, what RDBM would be the best fit?
Thanks

Here is a proposal for associating a value from one of two tables for each entry in mytable. I.e. this is making the assumption that mytable does not only contain a single entry for choosing the secondary table.
For details on what this means, see "MCVE" at the end of this answer.
If you want to switch between two secondary tables, based on a single entry in main table, see at the very end of this answer.
Details:
a hardcoded "value1"/"value2" as column1 added on the fly to the result from secondary tables
joining by the faked colummn1 and a secondary join-key, assumption here id
a union all to make a single table from both secondary tables (including the fake column1)
select *
from mytable
left join
(select 'value1' as column1, * from table1
UNION ALL
select 'value2' as column1, * from table2)
using(id, column1);
Output (for the MCVE provided below, "a-f" from table1, "A-Z" from table2):
value1|1|a
value2|2|B
value1|3|c
value1|4|d
value2|5|E
value2|6|F
MCVE:
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE mytable (column1 varchar(10), id int);
INSERT INTO mytable VALUES('value1',1);
INSERT INTO mytable VALUES('value2',2);
INSERT INTO mytable VALUES('value1',3);
INSERT INTO mytable VALUES('value1',4);
INSERT INTO mytable VALUES('value2',5);
INSERT INTO mytable VALUES('value2',6);
CREATE TABLE table2 (value varchar(2), id int);
INSERT INTO table2 VALUES('F',6);
INSERT INTO table2 VALUES('E',5);
INSERT INTO table2 VALUES('D',4);
INSERT INTO table2 VALUES('C',3);
INSERT INTO table2 VALUES('B',2);
INSERT INTO table2 VALUES('A',1);
CREATE TABLE table1 (value varchar(2), id int);
INSERT INTO table1 VALUES('a',1);
INSERT INTO table1 VALUES('b',2);
INSERT INTO table1 VALUES('c',3);
INSERT INTO table1 VALUES('d',4);
INSERT INTO table1 VALUES('e',5);
INSERT INTO table1 VALUES('f',6);
COMMIT;
For selecting between two tables based on a single entry in main table (in this case "mytable2":
select * from table1 where (select column1 from mytable2) = 'value1'
union all
select * from table2 where (select column1 from mytable2) = 'value2';
Output (with mytable2 only containing 'value1'):
a|1
b|2
c|3
d|4
e|5
f|6

Related

A sql query to create multiple rows in different tables using inserted id

I need to insert a row into one table and use this row's id to insert two more rows into a different table within one transaction. I've tried this
begin;
insert into table default values returning table.id as C;
insert into table1(table1_id, column1) values (C, 1);
insert into table1(table1_id, column1) values (C, 2);
commit;
But it doesn't work. How can I fix it?
updated
You need a CTE, and you don't need a begin/commit to do it in one transaction:
WITH inserted AS (
INSERT INTO ... RETURNING id
)
INSERT INTO other_table (id)
SELECT id
FROM inserted;
Edit:
To insert two rows into a single table using that id, you could do that two ways:
two separate INSERT statements, one in the CTE and one in the "main" part
a single INSERT which joins on a list of values; a row will be inserted for each of those values.
With these tables as the setup:
CREATE TEMP TABLE t1 (id INTEGER);
CREATE TEMP TABLE t2 (id INTEGER, t TEXT);
Method 1:
WITH inserted1 AS (
INSERT INTO t1
SELECT 9
RETURNING id
), inserted2 AS (
INSERT INTO t2
SELECT id, 'some val'
FROM inserted1
RETURNING id
)
INSERT INTO t2
SELECT id, 'other val'
FROM inserted1
Method 2:
WITH inserted AS (
INSERT INTO t1
SELECT 4
RETURNING id
)
INSERT INTO t2
SELECT id, v
FROM inserted
CROSS JOIN (
VALUES
('val1'),
('val2')
) vals(v)
If you run either, then check t2, you'll see it will contain the expected values.
Please find the below query:
insert into table1(columnName)values('stack2');
insert into table_2 values(SCOPE_IDENTITY(),'val1','val2');

SQL - return differences between rows (in two different tables) but ONLY if row ID exists in both tables

I have two tables that contain two potential differences which I'm trying to pick up on - rows that exist only in one of the tables, and rows that exist in both (sharing a common ID) but having different values for one of the columns (columns are exactly the same in both tables).
CREATE TABLE "MyTable1" (ID INTEGER, FIRST_NAME TEXT, DOB DATE);
INSERT INTO MyTable1 VALUES (1, "Tom", "01-02-18");
INSERT INTO MyTable1 VALUES (2, "Dick", "02-02-18");
INSERT INTO MyTable1 VALUES (3, "Larry", "03-02-18");
INSERT INTO MyTable1 VALUES (4, "Jebroni", "04-02-18");
CREATE TABLE "MyTable2" (ID INTEGER, FIRST_NAME TEXT, DOB DATE);
INSERT INTO MyTable2 VALUES (1, "Tom", "01-02-18");
INSERT INTO MyTable2 VALUES (2, "Dick", "02-02-18");
INSERT INTO MyTable2 VALUES (3, "Barry", "03-02-18");
I can return IDs in MyTable1 not present in MyTable2:
SELECT MyTable1.*
FROM MyTable1
WHERE MyTable1.ID NOT IN (SELECT MyTable2.ID FROM MyTable2)
Returns what I'm after:
ID FIRST_NAME DOB
"4" "Jebroni" "04-02-18"
For the second part I want to compare values of each column for rows sharing a common ID.
SELECT 'TABLE1' AS SRC, MyTable1.*
FROM (
SELECT * FROM MyTable1
EXCEPT
SELECT * FROM MyTable2
) AS MyTable1
UNION ALL
SELECT 'TABLE2' AS SRC, MyTable2.*
FROM (
SELECT * FROM MyTable2
EXCEPT
SELECT * FROM MyTable1
) AS MyTable2
This returns more than what I'm after - rows that exist in one table and not the other:
SRC ID FIRST_NAME DOB
"TABLE1" "3" "Larry" "03-02-18"
"TABLE1" "4" "Jebroni" "04-02-18"
"TABLE2" "3" "Barry" "03-02-18"
How should I tweak my last query so that the result is instead:
SRC ID FIRST_NAME DOB
"TABLE1" "3" "Larry" "03-02-18"
"TABLE2" "3" "Barry" "03-02-18"
I.e. restrict what's returns on the basis of the ID being present in both tables?
Restrict the first set of rows to those with a matching ID in the other table:
SELECT 'TABLE1' AS SRC, *
FROM (
SELECT * FROM MyTable1 WHERE ID IN (SELECT ID FROM MyTable2)
EXCEPT -------------------------------------
SELECT * FROM MyTable2
)
UNION ALL
SELECT 'TABLE2' AS SRC, *
FROM (
SELECT * FROM MyTable2 WHERE ID IN (SELECT ID FROM MyTable1)
EXCEPT -------------------------------------
SELECT * FROM MyTable1
);
I would just use join:
select *
from MyTable1 t1 join
MyTable2 t2
on t1.id = t2.id
where t1.firstname <> t2.firstname or t1.dob <> t2.dob;
I don't think set-based operations will do exactly what you want. But you can add to your query:
where id in (select id from mytable1 t1
intersect
select id from mytable2 t2
)
This will limit results to ids in both tables and you don't have to list out the rest of the columns.

Insert lost data to the table

I have two tables, which have two common column 'StationID'.
Create table t1(ID int, StationID bigint)
insert into t1 values
(0,1111),
(1,2222),
(2,34),
(3,456209),
(56,78979879),
(512,546)
go
Create table t2(StationID bigint, Descr varchar(50))
insert into t2 values
(-1,'test-1'),
(0,'test0'),
(1,'test1'),
(2,'test2'),
(5001,'dummy'),
(5002,'dummy'),
(6001,'dummy')
go
Now we notice that not every t1.StationID is in t2.StationID. Run the script can prove it.
select distinct StationID from t1 as A
where not exists
(select * from t2 as B where B.StationID =A.StationID)
The result is:
StationID
34
546
1111
2222
456209
78979879
Now I want to fill t2 with the lost StationID above, the column Descr can be any dummy data.
My real case has thousands records, how to use script to implement it?
insert into t2 (StationID, Descr)
select distinct StationID, 'dummy'
from t1 as A
where not exists
(select * from t2 as B where B.StationID =A.StationID)
INSERT INTO
t2
SELECT DISTINCT
stationid, 'dummy'
FROM
t1
WHERE
stationid NOT IN (SELECT stationid FROM t2)
(As an alternative to the others).

Copy data into another table

How to copy/append data from one table into another table with same schema in SQL Server?
Edit:
let's say there is a query
select *
into table1
from table2
where 1=1
which creates table1 with the same schema as well as data as in table2.
Is there any short query like this to only copy entire data only into an already existing table?
If both tables are truly the same schema:
INSERT INTO newTable
SELECT * FROM oldTable
Otherwise, you'll have to specify the column names (the column list for newTable is optional if you are specifying a value for all columns and selecting columns in the same order as newTable's schema):
INSERT INTO newTable (col1, col2, col3)
SELECT column1, column2, column3
FROM oldTable
Simple way if new table does not exist and you want to make a copy of old table with everything then following works in SQL Server.
SELECT * INTO NewTable FROM OldTable
This is the proper way to do it:
INSERT INTO destinationTable
SELECT * FROM sourceTable
INSERT INTO table1 (col1, col2, col3)
SELECT column1, column2, column3
FROM table2
Try this:
INSERT INTO MyTable1 (Col1, Col2, Col4)
SELECT Col1, Col2, Col3 FROM MyTable2
Try this:
Insert Into table2
Select * from table1
Insert Selected column with condition
INSERT INTO where_to_insert (col_1,col_2) SELECT col1, col2 FROM from_table WHERE condition;
Copy all data from one table to another with the same column name.
INSERT INTO where_to_insert
SELECT * FROM from_table WHERE condition;
INSERT INTO DestinationTable(SupplierName, Country)
SELECT SupplierName, Country FROM SourceTable;
It is not mandatory column names to be same.
CREATE TABLE `table2` LIKE `table1`;
INSERT INTO `table2` SELECT * FROM `table1`;
the first query will create the structure from table1 to table2 and second query will put the data from table1 to table2
Copy all columns from one table to another table:
INSERT INTO table2
SELECT * FROM table1
WHERE condition;
Copy only some columns from one table into another table:
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;
You can duplicate or "clone" a table's contents by executing:
CREATE TABLE new_table AS SELECT * FROM original_table;
-- for Sql Server users.
if you don't have the new table then you can create the new table with same structure as old table, and also copy data over from old table to the new table. For example:
select * into new_table
from old_table;
also you can copy the column / table structure, and just some of data. For example:
select * into new_table
from old_table
where country = 'DE';

How to select the record from table and insert into another table?

I wanted to select the last record from the table1 and insert into another table .Here is my query.
Insert into table2 values(select top 1 col1,col2 from table1 order by id desc).
I know for adding the value into table,need to be in cotation.But where to add?
You can select literals to fill in the other columns that table1 can't provide, something like this:
insert into table2 (col_a, col_b, col_c, col_d)
select top 1 col1, col2, 'foo', 'bar'
from table1
order by id desc
Any columns you do not name in the column list will get the default value, or null if no default is defined.
The number and type of columns selected must match the number and type of columns in the insert column list.
In SQL, there are essentially basically two ways to INSERT data into a table: One is to insert it one row at a time, the other is to insert multiple rows at a time. Let's take a look at each of them individually:
INSERT INTO table_name (column1, column2, ...)
VALUES ('value1', 'value2', ...)
The second type of INSERT INTO allows us to insert multiple rows into a table. Unlike the previous example, where we insert a single row by specifying its values for all columns, we now use a SELECT statement to specify the data that we want to insert into the table. If you are thinking whether this means that you are using information from another table, you are correct. The syntax is as follows:
INSERT INTO table1 (column1, column2, ...)
SELECT t2.column3, t2.column4, ...
FROM table2 t2
So, in you case, you can do it like this:
Insert into table2
select top 1 t1.col1,t1.col2 from table1 t1 order by id desc
Or you can use your syntax like this:
declare #col1 type_of_col1, #col2 type_of_col2
select top 1 #col1 = t1.col1, #col2 = t1.col2 from table1 t1 order by id desc
Insert into table2 values(#col1, #col2)
Offcourse, this all works assuming that the column datatypes are matched.