Mysql insert a row only if id exist in another table - mysql

I have 2 simple table
table1 -> p_id | s_id
table2 -> p_id | s_id
The two table are same. The p_id ai value.
I would like to insert into the table2 a row, but **only if p_id is exist in table1. This is possible? (MySQL)
INSERT INTO table1 (p_id, s_id)
SELECT * FROM (SELECT '100', '2') AS tmp
WHERE NOT EXISTS (SELECT p_id FROM table2 WHERE p_id = '100')
LIMIT 1

You can insert into a table based on any SELECT query. For example:
INSERT INTO table2 (p_id, s_id)
SELECT p_id, 2 FROM table1 WHERE p_id = 100;
If there are zero rows in table1 with the specified p_id value, this is a no-op. That is, it inserts zero rows into table2. If there is 1 row in table1 with that p_id value, it inserts into table2.
No need for LIMIT 1 because if p_id is the primary key then there is guaranteed to be only 1 or 0 rows with the given value.

Try This
Insert into table2 (p_id,s_id) Select p_id,'2' as s_id FROM table1 where p_id=100 LIMIT 1

Related

Not able to add multiple column against same ID in table

I have two tables x and y, x have the ID and many other columns, however y only have the ID similar as x table and then this ID is mapped to Many values
My Insert statement looks like this
INSERT INTO `table`
(`id`,
`other_name`)
VALUES
(select id from another_table where name = 'something'`,
('WALLETAB',
'SBTRADER',
'SBTRDACKING'));
expected result
1 | WALLETAB
1 | SBTRADER
1 | SBTRDACKING
I take ID from another table which already have data and this another table some different data associated with this table
You could fetch id from another table to be used in insert statement by using limit 1, something like:
select id from another_table where name = 'something' limit 1
However, to insert all 3 rows you will need a multiple insert in a single statement.
insert into `table` values
((select id from another_table where name = 'something' limit 1), 'WALLETAB'),
((select id from another_table where name = 'something' limit 1), 'SBTRADER'),
((select id from another_table where name = 'something' limit 1), 'SBTRDACKING');
See fiddle: https://www.db-fiddle.com/f/gYvrxdsDxVQPkZM2o8YRT1/1
It feels a lot of duplication. You can simplify it by either using variable or CTE. The following query utilizes CTE which only usable on mysql 8+:
insert into `table` (id, other_name)
with
other_id as (
select id from another_table where name = 'something'),
merged as (
select id, other_name from other_id join
(select 'WALLETAB' as other_name
union select 'SBTRADER'
union select 'SBTRDACKING')
as other_temp)
select * from merged;
The CTE above fetch the id on other_id. The union-select pairs is then used to create 3 rows containing 'WALLETAB', 'SBTRADER', and 'SBTRDACKING' respectively. Then both of them joined to get 3 rows with varying value on other_name but has id as 1.
See fiddle: https://www.db-fiddle.com/f/xgQta17bGphHAB81N2FNwX/1

Getting gender count from one table and inserting to another in Mysql

I am trying to take gender stats from table 1
table_1
and table 2
table_2
and insert into 'gender' table
gender
using the command :
INSERT INTO gender(Male) VALUES ((SELECT COUNT(*) FROM table_1 WHERE Gender = 'Male'),(SELECT COUNT(*) FROM table_2 WHERE Gender = 'Male'))
and
INSERT INTO gender(Female) VALUES ((SELECT COUNT(*) FROM table_1 WHERE Gender = 'Female'),(SELECT COUNT(*) FROM table_2 WHERE Gender = 'Female'))
But i keep getting an error: Column count doesn't match value count at row 1
The number of values passed and the number columns in the gender table don't match, hence the error.
Assuming the table gender has following columns -> gender, count_1, count_2
INSERT INTO gender(gender, count_1, count_2) VALUES ('Male', (SELECT
COUNT() FROM table_1 WHERE Gender = 'Male'),(SELECT COUNT() FROM
table_2 WHERE Gender = 'Male'))
INSERT INTO gender(gender, count_1, count_2) VALUES ('Female', (SELECT
COUNT() FROM table_1 WHERE Gender = 'Female'),(SELECT COUNT() FROM
table_2 WHERE Gender = 'Female'))
The error is telling your insert expects rows with one column, but your value has two.
INSERT INTO gender(Male) VALUES ( -- start of a row
-- Column 1
(SELECT COUNT(*) FROM table_1 WHERE Gender = 'Male'),
-- Column 2
(SELECT COUNT(*) FROM table_2 WHERE Gender = 'Male')
) -- end of a row
The problem is you have an extra set of parens making it one row with two columns. If you want to insert two rows, remove those parens.
INSERT INTO gender(Male) VALUES
(SELECT COUNT(*) FROM table_1 WHERE Gender = 'Male'), -- row 1
(SELECT COUNT(*) FROM table_2 WHERE Gender = 'Male'); -- row 2
The parens go around each row.

Add values to table1 for each element from table2 and using MAX(id) + 1 from table1 as table2 id

I have table1 and table2 and want to do something like the following:
INSERT INTO table1 (ID, OWNER_ID, NAME) SELECT (SELECT MAX(ID) FROM table1) + 1, ID, 'value' FROM table2
The query above does not work and returns:
Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.table1(ID)"; SQL statement:
Any help please?
table1:
| ID | OWNER_ID | NAME |
| --- | ---- | --- |
ŧable2:
| ID | OWNER_ID_REF | NAME |
| --- | ---- | --- |
Thanks
set #i:=(SELECT MAX(ID) FROM table1);
INSERT INTO table1 (ID, OWNER_ID, NAME) SELECT #i:=#i+1, ID, 'value' FROM table2
try this query it will work fine
It looks like ID is a primary key column in table1. Your current insert will most likely be inserting the same ID value multiple times, because the max subquery will have the same value for each record in table2. Assuming ID is auto increment, you probably should not be assigning a value to it anyway. Here is one option:
INSERT INTO table1 (OWNER_ID, NAME)
SELECT ID, 'value'
FROM table2;
You are using
SELECT (SELECT MAX(ID) FROM table1) + 1, ID, 'value' FROM table2
When you are inserting Through select
Max(ID)+1
give sample value all the records for table2
Use something like this...
Create table #tt( id int primary key ,Name varchar(200))
declare #vaue int = (select max(id) from #tt)
insert into #tt
select row_number() over(order by id) + #vaue
,Name from #tt

Left outer join not showing second table as null

Table structre
table 1
account
123
1234
12345
123456
table 2
account
123
1234
12345
I want to return table a record 123456 on account for table1 and null for column 2 when it doesnt match table 2
SQL
SELECT table1.account, table2.account
from table1
left outer join table2
on (table1.account= table2.account)
Your where statement explicitly asked for non-null rows with table2.dates = '19-jul-17'
You should modify your query to check for nulls:
SELECT
table1.account, table2.account
from table1
left outer join table2
on (table1.account= table2.account)
where
t1.dates='20170719'
and ( table2.account is NULL
or
table2.dates = '20170719'
)
This matches rows that have a specific date in the first table, and either null or a specific date on the second.
Note the date literal. The original query used a locale-specific format. This can fail easily faile in locales that don't use that format. Never mind the two digit year.
YYYYMMDD on the other hand is unambiguous.
UPDATE
Once the where clause is removed, NULLs are returned as expected :
declare #table1 table (id int)
declare #table2 table (id int)
insert into #table1
values
(123 ),
(1234 ),
(12345 ),
(123456)
insert into #table2
values
(123 ),
(1234 ),
(12345)
SELECT t1.id, t2.id
from #table1 t1
left outer join #table2 t2
on (t1.id= t2.id)
Returns
id id
123 123
1234 1234
12345 12345
123456 NULL
If the question is "how do I get the non-matching row" the answer is use WHERE tabl2.ID IS NULL
Everything is OK in your query, If you are using any where clause, please remove and check, BTW i am not able to reproduce your issue. PFB attempt, The query gives expected result
create table #tmp1( ID int)
create table #tmp2( ID int)
Insert into #tmp1 values('123')
Insert into #tmp1 values ('1234')
Insert into #tmp1 values ('12345')
Insert into #tmp1 values ('123456')
Insert into #tmp2 values('123')
Insert into #tmp2 values ('1234')
Insert into #tmp2 values ('12345')
select * from #tmp1
select * from #tmp2
SELECT #tmp1.ID, #tmp2.ID from #tmp1 left outer join #tmp2 on (#tmp1.ID=#tmp2.ID)
drop table #tmp1
drop table #tmp2
The result is:
ID ID
123 123
1234 1234
12345 12345
123456 NULL

combine 3 or more tables, deliberately without a joining condition

How do i join 3 or more tables in mysql as follows?
there is a column for each column of each table (except ID)
ID field values all go into the same ID field in the new table
an additional column is added called table the values of which is the source Table name
an autoincremented newID field is added
only one table contributes to each row, unrelated fields have null values
total number of rows is equal to the sum records from all tables
example with just two tables :
TableA: TableB
ID | fieldA ID | fieldB
----------------- -----------------
1 | valueA1 1 | valueB1
2 | valueA2 2 | valueB2
ResultTable:
newID | ID | table | fieldA | fieldB
---------------------------------------------
1 | 1 | TableA | valueA1 |
2 | 2 | TableA | valueA2 |
3 | 1 | TableB | | valueB1
4 | 2 | TableB | | valueB2
I know this probably sounds a bit weird!. I am going to try and use this to batch insert nodes for records from various tables into neojs graph database with this batch-insert script. which could be hilarious considering I hardly know what I am doing in either database ;-) .
Try this one,
SELECT #rownum := #rownum + 1 AS NewID,
a.*
FROM
(
SELECT ID, fieldA, '' AS fieldB
FROM tableA
UNION ALL
SELECT ID, '' AS fieldA, fieldB
FROM tableB
) a, (SELECT #rownum:=0) r
SQLFiddle Demo
Create New Table
here's the proposed schema
CREATE TABLE Newtable
(
NewID INT AUTO_INCREMENT,
ID INT NOT NULL,
FieldA VARCHAR(30),
FieldB Varchar(30),
CONSTRAINT tb_pk PRIMARY KEY (NewID)
)
then Insert your values,
here's the query using INSERT INTO...SELECT statement
INSERT INTO NewTable (ID, fieldA, fieldB)
SELECT ID, fieldA, NULL AS fieldB
FROM tableA
UNION ALL
SELECT ID, NULL AS fieldA, fieldB
FROM tableB
Create a table with auto increment newID
Add all the possible columns allowing nulls.
INSERT INTO it the values from TableA, then TableB with something like:
INSERT INTO table
(ID, `table`, fieldA)
SELECT ID, 'TableA', fieldA FROM TableA
INSERT INTO table
(ID, `table`, fieldB)
SELECT ID, 'TableB', fieldB FROM TableB
Use UNION to select all rows in one result set, INSERT INTO for inserting to new table.
Also you can get new ID using ROW_NUMBER() in sql server
SELECT ID, COL1, NULL, NULL FROM Table1
UNION
SELECT ID, NULL, COL2, NULL FROM Table2
UNION
SELECT ID, NULL, NULL, COL3 FROM Table3
Select above result to a temp table. Use row number to update new ID
SELECT ID, ... , ROW_NUMBER() OVER(ORDER BY ID) AS NewID FROM #TempTable