將多列結果插入到單列表中

[英]Insert multi column result into single column table


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.

我有一個包含三個列的表“movies”:“id”、“master_id”和“searchMe”(簡化)。我有另一個表'temp_ids',只有一個列:'id'。這是一張臨時的桌子,但我認為這並不重要。

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和每個master_id插入到“temp_ids”表中,但每次只插入一個。如果我的結果是

id_1 | master_1
id_2 | master_2
id_3 | NULL

I want my temp_ids to look like

我希望我的temp_id看起來像這樣

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.

我想把結果中的每一列都轉換成它自己的行。我怎樣才能優雅地做到這一點呢?我知道我可以在多個查詢中完成,分別搜索id和master_id,我知道我可以用PHP解決這個問題。但如果可能的話,我希望它能在一個mysql查詢中解決這個問題。

I made a sqlfiddle for this: http://sqlfiddle.com/#!2/b4a7f/2

我做了一個sqlfiddle: http://sqlfiddle.com/#!2/b4a7f/2。

2 个解决方案

#1


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

然后您就可以使用這個查詢來使用這個SELECT插入到temp中

#2


2  

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/09/19/eb7cb7a9e6898af76227f211261c1997.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com