使用“分隔条件”从多个表中选择多个列

时间:2014-07-15 13:51:36

标签: php mysql

我一直在使用mySQL,但到目前为止还没有真正想要这么高效。我目前有以下代码:

SELECT `page_name` AS manufacturer_name
FROM `manufacturers`
WHERE `id` = '$manufacturers_id'
UNION ALL
SELECT `page_name` AS series_name
FROM `series`
WHERE `id` = '$series_id'

不幸的是,这不是我想要的,它是为我选择正确的信息,但它只是在一个列名称:manufacturer_name。如何修改此选项以分别从制造商和系列中选择页面名称?这是我得到的当前输出:

manufacturer_name
my_manufacturer_name
my_series_name

这就是我想要的输出(注意:我只是将它用作列分隔符:|):

   manufacturer_name | series_name
my_manufacturer name | my_series_name

1 个答案:

答案 0 :(得分:1)

如果您的结果只包含单行,请使用

select 
(
  SELECT `page_name` AS manufacturer_name
  FROM `manufacturers`
  WHERE `id` = '$manufacturers_id'
) as manufacturer_name,
(
  SELECT `page_name` AS series_name
  FROM `series`
  WHERE `id` = '$series_id'
) as series_name

UNION的另一种可能性是

SELECT `page_name` AS manufacturer_name, null as series_name
FROM `manufacturers`
WHERE `id` = '$manufacturers_id'
UNION ALL
SELECT null, `page_name`
FROM `series`
WHERE `id` = '$series_id'

但这会返回2行。