简体   繁体   English

使用单独的条件从多个表中选择多个列

[英]Select Multiple Columns from Multiple Tables using Separate Where Conditions

I have been using mySQL for a while, but have not really wanted to be this efficient till now. 我已经使用mySQL一段时间了,但是到目前为止,我并不想真正做到如此高效。 I currently have the following code: 我目前有以下代码:

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'

Unfortunately this is not doing what I want, it is selecting the right information for me, but it is putting it all under just one column name: manufacturer_name. 不幸的是,这并没有满足我的要求,而是为我选择了正确的信息,但是所有这些都仅放在一个列名称下:Manufacturer_name。 How do I modify this to select the page name from manufacturers and series separately? 如何修改此名称以分别从制造商和系列中选择页面名称? This is the current output I am getting: 这是我得到的当前输出:

manufacturer_name
my_manufacturer_name
my_series_name

This is what I would like to have as output (Note: I just used this as a column separator: |): 这就是我想要作为输出的内容(注意:我只是将其用作列分隔符:|):

   manufacturer_name | series_name
my_manufacturer name | my_series_name

If your results contain only single row then use 如果您的结果仅包含一行,则使用

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

Another possibility with UNION is 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'

but this returns 2 rows. 但这会返回2行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM