在SQL案例表达式中返回'Then'子句的多个值

时间:2019-03-06 09:00:51

标签: mysql sql

我的“文件”表数据是

fileid   file1      file2
  1      abc.pdf    abcde.pdf
  2      ghf.pdf    ghfjkl.pdf
  3      hjy.pdf    hjyui.pdf

我的“样本表”数据是

 fileid       names
   1           abc
   2           ghf
   3           hjy
   4           juk

我需要类似

的输出
   fileid      names    files

     1          abc      abc.pdf
     1          abc      abcde.pdf
     2          ghf      ghf.pdf
     2          ghf      ghfjkl.pdf
     3          hjy      hjy.pdf
     3          hjy      hjyui.pdf

我尝试了以下查询,但没有得到想要的输出

 select st.fileid,st.contolnames,
 case when st.fileid in (select fileid from Files) 
 then f.file1 
 when st.fileid in (select fileid from Files)  then f.file2 end as Files
 from sampletable st
 join Files f on f.fileid=st.fileid 

请对此提供帮助 演示: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=08337e2ee351b573bc902f06fcfba272

3 个答案:

答案 0 :(得分:1)

您可以在下面尝试-使用UNION

DEMO

    select * from
    (
    select a.fileid,contolnames,file1 as files
    from Files a inner join sampletable b on a.fileid=b.fileid
    union
    select a.fileid,contolnames,file2 as files 
    from Files a inner join sampletable b on  a.fileid=b.fileid
  )A order by fileid

输出:

fileid  contolnames files
1         abc   abc.pdf
1         abc   abcdef.pdf
2         ghf   ghf.pdf
2         ghf   ghfjkl.pdf
3         hjy   hjyui.pdf
3         hjy   hjy.pdf

答案 1 :(得分:1)

要为每条记录生成两行,您可以像下面的查询一样使用CROSS JOIN来获得所需的输出。

select f.fileid, 
       st.contolnames as names, 
       case 
         when t.x = 1 then f.file1 
         else file2 
       end            as files 
from   Files f 
       inner join sampletable st 
               on st.fileid = f.fileid 
       cross join (select 1 x 
                   union 
                   select 2 x) t(x) 
order  by fileid 

Online Demo

答案 2 :(得分:0)

尝试这个。它对我有用。

CREATE TABLE #Temp1(fileid INT IDENTITY, file1 varchar(50), file2 varchar(50))
CREATE TABLE #Temp2(fileid INT IDENTITY, name varchar(50))
CREATE TABLE  #Temp3(fieldid int, name varchar(50), file1 varchar(50) , file2 varchar(50))
create table #Temp4 (fieldid int, name varchar(50), files varchar(50))  

INSERT INTO #Temp1 VALUES( 'abc.pdf','abcde.pdf')
INSERT INTO #Temp1 VALUES( 'ghf.pdf','ghfjkl.pdf')
INSERT INTO #Temp1 VALUES( 'hjy.pdf','hjyui.pdf')


INSERT INTO #Temp2 VALUES( 'abc')
INSERT INTO #Temp2 VALUES( 'ghf')
INSERT INTO #Temp2 VALUES( 'hjy')
INSERT INTO #Temp2 VALUES( 'juk')

SELECT * FROM #Temp1
SELECT * FROM #Temp2


INSERT INTO #Temp3
SELECT * FROM (SELECT B.fileid ,name , 
CASE WHEN Name Like SUBSTRING(A.file1,1,3) THEN file1  END AS files, 
CASE WHEN Name Like SUBSTRING(A.file2,1,3) THEN  file2 END AS files1   
FROM #Temp1 A , #Temp2 B ) AA WHERE files IS NOT NULL

INSERT INTO #Temp4 SELECT fieldid,name,file1 FROM  #Temp3 

INSERT INTO #Temp4 SELECT fieldid,name,file2 FROM  #Temp3 

SELECT * FROM #Temp4 ORDER BY name asc

DROP TABLE #Temp1
DROP TABLE #Temp2
DROP TABLE #Temp3
DROP TABLE #Temp4