MySQL - 从两个不同的表重命名具有相同名称的选定列

时间:2014-10-11 01:28:02

标签: php mysql

我从两个不同的表中选择了相同的列,但想要使用select as使它们具有不同的名称。

(SELECT letter AS letter_1, sex AS sex_1 FROM `celebs_a` LIMIT 1)
UNION
(SELECT letter AS letter_2, sex AS sex_2 FROM `celebs_b` LIMIT 1)

该查询返回:

letter_1 sex_1
a        1
b        1

但是,我想让它归还:

letter_1 letter_2 sex_1 sex_2
a        b        1     1

如何使该查询将每个值作为不同的列名返回?感谢。

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT 
    (SELECT letter AS letter_1 FROM `celebs_a` LIMIT 1) AS letter_1,
    (SELECT letter AS letter_2 FROM `celebs_b` LIMIT 1) AS letter_2;

更新:

SELECT 
    (SELECT letter ... FROM celebs_a ...) AS letter_1,
    (SELECT letter ... FROM celebs_b ...) AS letter_2,
    (SELECT sex ... FROM celebs_a ...) AS sex_1,
    (SELECT sex ... FROM celebs_b ...) AS sex_2

或者Barmars的方法会更好(它只运行2个SELECT查询)

答案 1 :(得分:1)

SELECT MAX(letter_1) AS letter_1, MAX(sex_1) AS sex_1,
       MAX(letter_2) AS letter_2, MAX(sex_2) AS sex_2
FROM (
    (SELECT letter AS letter_1, '' AS letter_2, sex AS sex_1, 0 AS sex_2
     FROM celebs_a
     LIMIT 1)
    UNION
    (SELECT '' AS letter_1, letter AS letter_2, 0 AS sex_1, sex AS sex_2
     FROM celebs_b
     LIMIT 1)
) AS derived_table_must_have_an_alias

您可以轻松地将其扩展为从每个表中选择多个列。只需将0''作为另一个表中这些列的占位符。