INSERT INTO (SELECT & VALUES) TOGETHER - mysql

I'm trying to INSERT INTO a table, and I know 2 ways:
Adding rows as values:
INSERT INTO db_example.tab_example (id,name,surname,group)
VALUES ('','Tom','Hanks','1');
or from another table:
INSERT INTO db_example.tab_example (id,name,surname)
SELECT ID,first_name,last_name FROM db_contacts.tab_mygroup;
but what if I want to insert some values from another table (the second way), and some values manually like a default value (the first way).
here's my try (it didn't work):
INSERT INTO db_example.tab_example (id,name,surname,group)
VALUES (
SELECT ID FROM db_contacts.tab_mygroup,
SELECT first_name FROM db_contacts.tab_mygroup,
SELECT last_name FROM db_contacts.tab_mygroup,
'1'
);
I thought of creating a VIEWtable and it might solve the problem, but I thought there might be someway to add both together.
Thank you guys! I hope I described well what I need :)

Just return the literal value from the SELECT statement; add an expression to the SELECT list. For example:
INSERT INTO db_example.tab_example (id,name,surname,group)
SELECT ID
, first_name
, last_name
, '1' AS group
FROM db_contacts.tab_mygroup;
FOLLOWUP
Q: can I SELECT first_name and last_name in the same column using the AS function? or I need another function?
A: If you want to combine the values in the first_name and last_name into a single column, you could concatenate them using an expression, and use that expression in the SELECT list, e.g
CONCAT(last_name,', ',first_name')
or
CONCAT(first_name,' ',last_name)
The AS keyword won't have any effect in the context of an INSERT ... SELECT, but assigning an alias to that expression that matches the name of the column the expression is being inserted into does serve as an aid for the future reader.
INSERT INTO db_example.tab_example (id,name,surname,group,full_name)
SELECT ID
, first_name
, last_name
, '1' AS group
, CONCAT(first_name,' ',last_name) AS full_name
FROM db_contacts.tab_mygroup

Try this
INSERT INTO db_example.tab_example (id,name,surname)
SELECT id,first_name,'M. Nega'
FROM db_contacts.tab_mygroup
You can use join in the FROM clause. It should work!

Related

How to sort the string on the basis of numbers?

I am working on the sql query in which I want to sort the string on the basis of numbers.
I have one column (Column Name is Name) table in which there are multiple fields. On using ORDER BY NAME, it prints in the following way:
hello_world
hello_world10
hello_world11
hello_world12
hello_world13
hello_world14
hello_world15
hello_world4
hello_world5
For the above query, I have used ORDER BY NAME; but it doesn't seem to print on the basis of numbers.
Problem Statement:
I am wondering what sql query I need to write or what changes I need to make in my sql query above so that it prints everything on the basis of numbers, the o/p should be this:
hello_world
hello_world4
hello_world5
hello_world10
hello_world11
hello_world12
hello_world13
hello_world14
hello_world15
you want a numeric ordering, then you need to create a numeric value to order on.
currently you have strings.
if the pattern is true, then you can use a combination of string manipulation to trim off the first characters, which should leave only numbers, then use TO_NUMBER() to convert for the ordering
something like
select name
from mytable
order by to_number( replace( name, 'hello_world','' ))
I think the simplest solution for this particular case (where all the values have the same prefix) is:
order by length(name), name
Try this:
SELECT name,
CASE WHEN REGEXP_INSTR(name, '[0-9]') = 0 THEN 0
ELSE CAST(SUBSTR(name, REGEXP_INSTR(name, '[0-9]')) AS INT)
END AS progressive
FROM my_table
ORDER BY progressive;
we can order it using replace and cast methods.
I tried the following query
select Name, cast(REPLACE(Name, 'hello_world', '') as UNSIGNED ) as repl from Users order by repl;
To generage sample data
CREATE TABLE Users (
Name varchar(255) NOT NULL
);
insert into Users(Name) values
('hello_world'),
('hello_world4'),
('hello_world5'),
('hello_world10'),
('hello_world11'),
('hello_world12'),
('hello_world13'),
('hello_world14'),
('hello_world15')
;
EDIT
query without replaced column,
select City from Persons order by cast(REPLACE(City, 'hello_world', '') as UNSIGNED );
Though the question is about mysql.
I tried in sql server.
create table #t1 (id varchar(100));
insert into #t1 (id) values ('Pq1'),('pq3'),('pq2')
select * from #t
order by
CAST(SUBSTRING(id + '0', PATINDEX('%[0-9]%', id + '0'), LEN(id + '0')) AS INT)

SQL Help | The select list for the INSERT statement contains fewer items than the insert list

Please see my query below,
insert into dbo.orderDetails(orderNo,clientId,productId,quantity)
values(' ee941422-5546-4d62-b5d6-60ecd13ca2b8 ')
select client_id,product_id,amount from dbo.cart
where client_id =' efc08f7c-fdfc-4712-9488-fc1c55acb95e ' ;
In this I want a static orderno and the rest should come from the a table(dbo.cart).when i execute my query its shows this error
There are more columns in the INSERT statement than values specified in the
VALUES clause. The number of values in the VALUES clause must match the
number of columns specified in the INSERT statement.
Any solution.
You can't have both VALUES and SELECT. If you want to insert static values, put it into the SELECT list.
insert into dbo.orderDetails(orderNo,clientId,productId,quantity)
select ' ee941422-5546-4d62-b5d6-60ecd13ca2b8 ', client_id,product_id,amount from dbo.cart
where client_id =' efc08f7c-fdfc-4712-9488-fc1c55acb95e ' ;
My issue has been resolved, Below is the query which is working for me
INSERT INTO Exam_Trigger(Questions,CAT_ID,TOPIC_ID,SCHEDULED_TYPE,UPDATE_USER,UPDATE_DT,CREATE_USER,CREATE_DT)
select id ,'2','2','Weekly','',curdate(),'',curdate() from ( select GROUP_CONCAT(id SEPARATOR ',')as id from(select id from question_data order by rand() limit 4)as ls) as ps

count of distincts substring in query

I'm trying to create a query that count (or at least retrieve) distincts occurrences of a substring in a column.
I have one column that is like this:
elem1=value1|elem2=value2|elem3=value3
I want to retrieve distincts values of elem2 and the number of ocurrences.
SELECT
substring(
column , LOCATE( 'elem2=' , column ) + $1 , $2
) AS a ,
COUNT(*) b ,
FROM
column ORDER BY a;
Thanks
Here's one way to achieve the specified result.
SELECT COUNT(DISTINCT SUBSTRING_INDEX(SUBSTRING_INDEX(t.col,'elem2=',-1),'|',1))
FROM t
WHERE t.col LIKE '%elem2=%'
Apparently, I misread the question (the query above returns a count of distinct values. Or, I just lost track of the specified result, while I was working on the tedious string parsing.
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(t.col,'elem2=',-1),'|',1) AS a
, COUNT(*) AS b
FROM t
WHERE t.col LIKE '%elem2=%'
GROUP BY SUBSTRING_INDEX(SUBSTRING_INDEX(t.col,'elem2=',-1),'|',1)
ORDER BY SUBSTRING_INDEX(SUBSTRING_INDEX(t.col,'elem2=',-1),'|',1)
NOTE:
Note that SQL wasn't really designed for parsing values out of strings.
The normative relational pattern for this type of data would to create a table, with columns named elem1, elem2, elem3, and to store each separate value in a column.
For example:
CREATE TABLE t
( id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY
, elem1 VARCHAR(80)
, elem2 VARCHAR(80)
, elem3 VARCHAR(80)
);
INSERT INTO t (elem1, elem2, elem3) VALUES ('value1', 'value2', 'value3');
To get a count of distinct values in elem2 column, we'd do something like this.
SELECT COUNT(DISTINCT elem2)
FROM t
To get the distinct values of elem2 along with the count of occurrences
SELECT elem2 AS a
, COUNT(*) AS b
FROM t
GROUP BY elem2
ORDER BY elem2
That's essentially the same as the query at the beginning of my answer; the first query just has to do the parsing the 'elem2=value2' out of the string.

Query for first result in a column - substring_index function - MySQL

I can't seem to get the substring_index() to work:
I have created a simple table as follows:
CREATE TABLE ContactList(
cont_id int(11) NOT NULL AUTO_INCREMENT,
last_name varchar(30),
first_name varchar(20),
interests varchar(100),
PRIMARY KEY(cont_id));
I then populated the ContactList table as follows:
INSERT INTO ContactList (last_name, first_name, interests)
VALUES
('Murphy', 'Dave', 'Golf, Pets, Basketball'),
('Murphy', 'Ben', 'Pets, Gym, Basketball'),
('Finn', 'Belinda', 'Pets, Tennis, Knitting'),
('Murphy', 'Steve', 'Pets, Archery, Fishing');
I ran a quick SELECT to ensure the data was entered correctly:
SELECT * FROM ContactList;
Then I ran the following query:
SELECT * FROM ContactList
WHERE last_name = 'Murphy'
AND SUBSTRING_INDEX(interests, ',' ,1) = 'Pets';
I was expecting to get two records back (which I did for Ben & Steve), however, for the 'Interests' column I was assuming I should only get one interest back if it equaled 'pets' (due to the substring_index) however, I got all interests back. How can I use the SUBSTRING_INDEX() to run the query and only get the first interest listed back for each record if it says 'Pets'?
BTW I am using MySQL Version 5.5.24 and I know the Interests would be best suited in their own table - I just want to see why substring_index is not picking the first item from the list if it equals 'pets'.
Thanks for any input,
Andy R ;-)
You're using SUBSTRING_INDEX in the WHERE clause, which determines which rows to include. That's good, but you also need to use it in the SELECT clause, which determines which columns to include.
Try this:
SELECT
last_name,
first_name,
SUBSTRING_INDEX(interests, ',' ,1) AS FirstInterestInList
FROM ContactList
WHERE last_name = 'Murphy'
AND SUBSTRING_INDEX(interests, ',' ,1) = 'Pets';
Although substring_index() will work for the first element, you really want find_in_list():
SELECT last_name, first_name, SUBSTRING_INDEX(interests, ',' ,1) AS FirstInterestInList
FROM ContactList
WHERE last_name = 'Murphy' and
find_in_set('pets', interests) = 1
The advantage of find_inset() is that it will work for arbitrary positions.
Just as a note, though, your delimiter is ', '. For find_in_set() to work best, you should have no space after the column.
Also, if you are doing queries like this, you should fix your data structure. It really wants a table called something like ContactInterests which contains one row for each contact and each interest.

MySQL: Using variable on a WHERE IN clause

I'm becoming mad trying to use an "array" of values obtained from a GROUP_CONCAT into a WHERE IN statement, when GROUP_CONCAT only takes one "id" it works ok but when it takes more it doesn't.
As it follows:
START TRANSACTION;
DECLARE #coupon_ids VARCHAR(MAX);
-- Take one or more ids
SET #coupon_ids:=(SELECT IFNULL( (SELECT GROUP_CONCAT(coupon_id) FROM some_table WHERE order_id=(SELECT entity_id FROM sales_order WHERE increment_id=310033638) GROUP BY order_id), (SELECT coupon_id FROM some_table WHERE coupon_id=310033638)));
SELECT #coupon_ids;
INSERT INTO some_table_gift VALUES (NULL,TRIM('whatever'),'','');
SET #lastid:=LAST_INSERT_ID();
-- Here if #coupon_ids is just one id, like 123 it works, if it is a list of them like 123,234,254 it doesn't works
UPDATE some_table SET owner_id=#lastid,is_gift=1 WHERE coupon_id IN (#coupon_ids);
COMMIT;
-- Same here
SELECT coupon_id,owner_id,is_gift FROM some_table WHERE coupon_id IN (#coupon_ids);
Does anyone know how to work with this?
Thanks!
What's your filed type for coupon_id, if it is not any number type than it will not work.
One way you can add quote (single quote) for each result in GROUP_CONCAT Write
GROUP_CONCAT(coupon_id SEPARATOR '","')
remove SELECT #coupon_ids
And
in QUERY try this WHERE coupon_id IN ("#coupon_ids")