Insert multi column result into single column table - mysql

I have a table 'movies' with three Columns: 'id', 'master_id' and 'searchMe' (simplified). I have another Table 'temp_ids' with a single column: 'id'. It is a temporary table, but I don't think that matters.
When I make a query on my table 'movies' like
SELECT `id`, `master_id` FROM 'movies' WHERE searchMe = '1';
I get a multi column result. Now I want to insert every id and every master_id into the 'temp_ids'-Table, but one at a time. So if my result is
id_1 | master_1
id_2 | master_2
id_3 | NULL
I want my temp_ids to look like
id_1
master_1
id_2
master_2
id_3
So I want to convert every single column in the result into its own row. How can I do that in an elegant way?
I know I can do it in multiple queries, searching for id and master_id separatly, and I know I can solve that problem with PHP or so. But I would prefer it to solve that problem in a single mysql-query, if such a thing is possible.
I made a sqlfiddle for this:
http://sqlfiddle.com/#!2/b4a7f/2

To SELECT the data you can use a UNION ALL for this:
SELECT `id`
FROM movies
WHERE searchMe = 1
union all
SELECT `master_id`
FROM movies
WHERE searchMe = 1
and master_id is not null
see SQL Fiddle with Demo
Doing it this way, you cannot distinguish between what value comes from each column, so you can always add an indicator, this will give you two columns but then you know where the data came from:
SELECT `id`, 'id' type
FROM movies
WHERE searchMe = 1
union all
SELECT `master_id`, 'master'
FROM movies
WHERE searchMe = 1
and master_id is not null
Then you would just use this query to INSERT INTO temp using this SELECT

It would be like this
INSERT INTO temp_ids(id)
SELECT id
FROM
(
SELECT id
FROM FirstTable
UNION
SELECT master AS id
FROM SecondTable
) t

Related

SQL: Return immediately if one matched record found

I have one table with user and their posts. It looks like "user_id | post_id | post_status".
Now I have a list of userid (ex, 100 users) and I want to know how many of them has at least one post that gets deleted (ex, post_status 3).
Here is my sample search:
select count(distinct user_id)
from post_table
where user_id in ( {my set} )
and post_status=3
It runs super slow since it iterates the entire table. Is there a way to speed up the query?
Use something like
SELECT COUNT(*)
FROM
-- the list of userid as a rowset
( SELECT 123 AS user_id UNION ALL
SELECT 456 UNION ALL
-- ...
SELECT 789
) user_id_list
WHERE EXISTS ( SELECT NULL
FROM post_table
WHERE post_table.user_id = user_id_list.user_id
AND post_table.post_status = 3 )
If your MySQL version is 8.0.4 or above then you may provide the users list as CSV/JSON and parse it using JSON_TABLE (the query text will be more compact).
INDEX(post_status, user_id)
may help speed up your query, especially if very few rows have status=3.
This could also speed up Akina's solution.

Select from 2 database remove same column

I need to select all the values of table 1 from the first database that are not present in table 2 from the second database. I tried the code below, but DISTINCT does not work:
select DISTINCT(affected_ci),ci_name from sitequota.incidents,appwarehouse.ci_table where incidents.affected_ci <> ci_table.ci_name
DATABASE1: APPWAREHOUSE
TABLE1: CI_TABLE
COLUMN: CI_NAME
DATABASE2: SITEQUOTA
TABLE2: INCIDENTS
COLUMN: AFFECTED_CI
You could try something like:
SELECT ci_name
FROM appwarehouse.ci_table
WHERE ci_name NOT IN
(SELECT affected_ci FROM sitequota.incidents
)

MySQL INSERT INTO table 1 SELECT table 2 with different column name

I have a table (pdt_1) in database (db_1) and another table (pdt_2) in another database (db_2).
I met pdt_1 and pdt_2 to find pdt_1 products not present and published in pdt_2.
functional code :
SELECT * FROM db_1.pdt_1 AS lm
WHERE lm.product_sku
NOT IN (SELECT DISTINCT product_cip7 FROM db_2.pdt_2)
AND lm.product_publish=‘Y'
finally, I need to insert the result of this query in pdt_2.
However, the structure of pdt_1 and pdt_2 are different.
Example:
- columns's names
- columns's numbers
I also need an auto_increment id for pdt_1 products inserted into pdt_2.
I need help.
NB : sorry for my poor english :(
If you want a new table with just the id and product_sku, try:
INSERT INTO new_table # with id and product_sku from first table
SELECT pdt_1.id,
pdt_1.product_sku
FROM db_1.pdt_1
LEFT JOIN db_2.pdt_2
ON pdt_1.product_sku = pdt_2.product_cip7
WHERE pdt_2.product_cip7 IS NULL
AND pdt_1.product_publish = 'Y'

Get a list of ids not present in a table

I have a list of ids, and I want to query a mysql table for ids not present in the table.
e.g.
list_of_ids = [1,2,4]
mysql table
id
1
3
5
6
..
Query should return [2,4] because those are the ids not in the table
since we cant view ur code i can only work on asumption
Try this anyway
SELECT id FROM list_of_ids
WHERE id NOT IN (SELECT id
FROM table)
I hope this helps
There is a horrible text-based hack:
SELECT
substr(result,2,length(result)-2) AS notmatched
FROM (
SELECT
#set:=replace(#set,concat(',',id,','),',') AS result
FROM (
select #set:=concat(',',
'1,2,4' -- your list here
,',')
) AS setinit,
tablename --Your tablename here
) AS innerview
ORDER BY LENGTH(result)
LIMIT 1;
If you represent your ids as a derived table, then you can do this directly in SQL:
select list.val
from (select 1 as val union all
select 2 union all
select 4
) list left outer join
t
on t.id = list.val
where t.id is null;
SQL doesn't really have a "list" type, so your question is ambiguous. If you mean a comma separated string, then a text hack might work. If you mean a table, then something like this might work. If you are constructing the SQL statement, I would advise you to go down this route, because it should be more efficient.

MySQL: Insert using results of Select field from pair clause

I've got a requirement to add an additional item of data to an existing row and insert the result in a second table. The data item is different for each row I am selecting, so I can't just add it to the SELECT statement. The original query is:
SELECT player_id,token_id,email FROM players
WHERE token_id in (101,102) OR email in ("test4#test.com");
I'd like to be able to do something like a Row Constructor and write the query something like this:
SELECT player_id,token_id, email, key_val FROM players
WHERE (token_id, key_val) in ( (101, 'xyz'),(102,'abc'))
OR (email, key_val) in ( ("test4#test.com", 'qpr') );
So that the second value ('key_val') from the pair in the IN clause would be added into the SELECT output as the last column. And then the whole lot will get inserted into the final table.
The number of items in the IN clause will vary from 3 to potentially 100's.
Really sorry if this is a dup. I've looked up things like:
Select Query by Pair of fields using an in clause
MySQL: How to bulk SELECT rows with multiple pairs in WHERE clause
I guess I could use a temporary table but I'm concerned about the number of times that this is going to be called.
Edit--
To clarify, the source table is something like:
player_id, token_id, email
===================================
1 101 null
2 102 null
3 null test4#test.com
and the date being supplied is:
(token_id=101, key_val='xyz'),(token_id=102, key_val='abc'),(email='test4#test.com', key_val='qpr')
and the intended output would be:
player_id token_id email keyy_val
========== ========= ============== ========
1 101 null zyz
2 102 null abc
3 null test4#test.com qpr
Hope this makes it clearer.
try this
SELECT player_id,token_id, email, key_val
FROM players
WHERE token_id in (101,102) AND key_val IN ('xyz','abc')
OR ( email in ("test4#test.com") AND key_val IN ('qpr') );
EDIT -.
try this
SELECT player_id,token_id, email, key_val
FROM ( select player_id,token_id, email,
if(`token_id` =101 , 'xyz',
if(`token_id` =102 , 'abc' ,
if(email = "test4#test.com" , 'qpr' , NULL))
) key_val
from players
)p
DEMO SQLFIDDLE