MySQL的。选择列为column1,其中... union all选择列为column2 where ...仅查看column1(不是column2)

时间:2015-06-02 05:45:44

标签: mysql

这里放置了示例http://sqlfiddle.com/#!9/af548/2

有桌子

NumberRenamed | TopicName | LanguageId    

1               Topic en      1
2               Topic es      2
3               Topic es1     2

查询

SELECT `TopicName` AS `TopicName1` FROM `topics` WHERE `LanguageId` = 1

UNION ALL

SELECT `TopicName` AS `TopicName2` FROM `topics` WHERE `LanguageId` = 2

;

期待获得数组,比如

Array
(
[0] => Array
    (
        [TopicName1] => Topic en
    )
[1] => Array
    (
        [TopicName2] => Topic es
    )
[2] => Array
    (
        [TopicName2] => Topic es1
    )

)

但请参阅

Array
(
[0] => Array
    (
        [TopicName1] => Topic en
    )
[1] => Array
    (
        [TopicName1] => Topic es
    )
[2] => Array
    (
        [TopicName1] => Topic es1
    )

)

仅查看[TopicName1](无[TopicName2]

我的查询有什么问题(需要纠正什么)?

2 个答案:

答案 0 :(得分:1)

如果使用UNION,列名将仅取自第一个“select”语句。您的查询没有任何问题。

答案 1 :(得分:1)

您可以尝试使用SQL CASE Expression

SQL Fiddle

SELECT CASE `LanguageId` 
     WHEN '1' THEN 'TopicName1'
     WHEN '2' THEN 'TopicName2'
     END AS Topic,
    `TopicName`
 FROM Topics;

获取输出

|      Topic | TopicName |
|------------|-----------|
| TopicName1 |  Topic en |
| TopicName2 |  Topic es |
| TopicName2 | Topic es1 |