从多个列中选择多行作为一列

时间:2015-01-05 13:53:51

标签: mysql sql select union where

正如标题所示,我试图从Passive,Q,W,E,R中选择非空的行到一列中 http://i.imgur.com/SzNl9WI.png这就是我尝试过没有运气的事情

SELECT (Passive + Q + W + E + R) AS spellchamps
FROM champions 
WHERE Patch_No='0.02' AND Champion = 'Katarina'
AND (
(Passive!='')
or(Q!='')
or(W!='')
or(E!='')
or(R!='')
)

如果我能将它与我之前的查询结合起来会更好,它可以选择非空列的名称

SELECT column_name 
                        from information_schema.columns, patches.champions
                        where 
                        table_name = 'champions'
                        AND ((column_name ='Passive' and Passive!='')
                        or (column_name='Q' and Q!='')
                        or (column_name='W' and W!='')
                        or (column_name='E' and E!='')
                        or (column_name='R' and R!='')

                        )

                         AND Patch_No = '0.02'
                        AND Champion = 'Katarina'

编辑这个查询给了我正确的结果,但是在一行中,我希望结果在不同的行中

SELECT CONCAT(Passive, Q, W, E, R) AS spellchamps
FROM champions 
WHERE Patch_No='0.02' AND Champion = 'Katarina'
AND (
(Passive!='')
or(Q!='')
or(W!='')
or(E!='')
or(R!='')
)

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT Passive AS spellchamps
FROM champions 
WHERE Patch_No='0.02' AND Champion = 'Katarina' AND 
      Passive IS NOT NULL AND Passive != ''
UNION 
SELECT Q AS spellchamps
FROM champions 
WHERE Patch_No='0.02' AND Champion = 'Katarina' AND 
      Q IS NOT NULL AND Q != ''
UNION 
SELECT W AS spellchamps
FROM champions 
WHERE Patch_No='0.02' AND Champion = 'Katarina' AND 
      W IS NOT NULL AND W != ''
UNION 
SELECT E AS spellchamps
FROM champions 
WHERE Patch_No='0.02' AND Champion = 'Katarina' AND 
      E IS NOT NULL AND E != ''
UNION 
SELECT R AS spellchamps
FROM champions 
WHERE Patch_No='0.02' AND Champion = 'Katarina' AND 
      R IS NOT NULL AND R != ''

答案 1 :(得分:0)

您可以使用CONCAT

SELECT CONCAT(Passive, Q,  W, E,  R) AS spellchamps
FROM champions 
WHERE Patch_No='0.02' AND Champion = 'Katarina' 
AND '' NOT IN (Passive, Q, W, E, R)