INSERT from SELECT statement, column count - mysql

Table1 has one column and table2 has three columns. The names are all unique.
INSERT INTO table2 (SELECT * FROM table1 WHERE name = 'Brian')
#1136 - Column count doesn't match value count at row 1
What is the easiest way to append NULL or empty strings to the results of the SELECT query?
I have tried this and many other variations:
INSERT INTO table2 (SELECT * FROM test WHERE name = 'Brian', '','')
INSERT INTO test2 ((SELECT * FROM test WHERE name = 'Brian') + '' , '')

The easiest way is to specify the column names in both source and target tables:
INSERT INTO table2 (col2) -- change col2 to the name of the column in table2 that will receive the values
SELECT col1 -- change col1 to the name of the column in table1
FROM table1
WHERE name = 'Brian';
All other than col2 columns in table2 will be set to null or their default values (if defined in the table's definition).
Even if col1 is the only column in table1, you should prefer SELECT col1 over SELECT *, because if you add any columns to the table SELECT * would stop working.

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

Select last duplicate row in MySQL

SELECT Duplicate row item from MySQL table using
SELECT * FROM `table` GROUP BY `col1`,`col2` Having COUNT(`col1`)>1 and COUNT(`col2`)>1
Actual result
The above query return first duplicate entry. from above data row 1 and row 7 contains duplicate field in same column(col1, col2).
But I need to Get last duplicate entry. Highlighted duplicate row
Expected Result
I need to get last duplicate entry.
How do you define the last duplicate? In a database table, records are not inhenrently ordered, and you did not tell which column we should use for ordering.
If you want to order by col3, then you can just use aggregation, like so:
select col1, col2, max(col3) -- or min(col3)
from mytable
group by col1, col2
-- having count(*) > 1
-- uncomment the above line if you want to see only records for which a duplicate exists
If you have some other column that you want to order with, say id, then you can filter with a correlated subquery
select col1, col2, col3
from mytable t
where id = (
select max(id) from mytable t1 where t1.col1 = t.col1 and t1.col2 = t.col2
)

UPDATE WHERE IN() mysql

I have a table called tableA containing two columns, 1,2. I am trying to remove from column 1 a value depending on whats in the array. If that value exists twice, I want to set col1 as col1 = col1 - 2.
I could use UPDATE tableA SET col1 = col1 - 1 WHERE col2 IN (?); .. [arr] and be on my way, if WHERE IN () didnt ignore duplicate values on the array.
Let me also note that this isnt about primary or unique keys and there is no problem with duplicate values. Below is the query where X is where I need to fix.
UPDATE tableA SET col1 = col1 - X WHERE col2 IN (?); .. [arr]
I know I can loop for the arr and run a simple query like: UPDATE tableA SET col1 = col1 - 1 WHERE col2 = ? ; .. [arr[i]] each time but am trying to find a better way - if there is.
You could use UPDATE ... JOIN:
UPDATE tableA a
JOIN (SELECT id, COUNT(*) cnt
FROM (SELECT 1 AS id UNION ALL SELECT 1 UNION ALL SELECT 1
UNION ALL SELECT 2 UNION ALL SELECT 2) x -- here goes IN values
GROUP BY id
)s
ON a.col2 = s.id
SET a.col1 = a.col1 - cnt;
DBFiddle Demo

MYSQL: Insert one value from another table while populating other columns regularly

Lets say we have a table (1):
id | col1 | col2
And another table (2):
id | col3
Task is to insert all col3 distinct values to col1 at the same time populating col2 with random integer value
A couple of solutions here.
This uses a sub query to return the distinct values of col2.
INSERT INTO table1 (id, col1, col2)
SELECT NULL, col2, FLOOR(RAND()*(1000))+1
FROM
(
SELECT DISTINCT col2
FROM table2
)
The following abuses the GROUP BY clause to only generate rows for distinct values of col2. While this should be OK on a default install of MySQL, it might not work depending on the options set up for your installation and also probably wouldn't work in other flavours of SQL.
INSERT INTO table1 (id, col1, col2)
SELECT NULL, col2, FLOOR(RAND()*(1000))+1
FROM table2
GROUP BY col2

whats wrong with this mysql insert query?

insert into tblcustomermachine
(
select * from
((select vch_CustomerID from tblcustomer where tblcustomer.vch_CustomerID='Cust00001' )
union all
(select Rate from tblmachine)) as t );
that table contains 18 cols and this resultset also contains 18 rows yet it shows " Column count doesn't match value count at row 1" . why?
It looks like your table tblcustomermachine has more then the 1 column.
Like Simone answered, update your insert to INSERT INTO tblcustomermachine(col_1) SELECT ...
You may skip the column names during INSERT, however the SELECT needs to return the same amount of columns that the table holds.
AFAIK, you have to declare field name:
insert into tblcustomermachine (col_1, col_2, col_3, ... col_18) (
select t.field1, t.field2, t.field3, ... t.field18 from (
(select vch_CustomerID from tblcustomer where tblcustomer.vch_CustomerID='Cust00001')
union all (select Rate from tblmachine))
as t
);