简体   繁体   中英

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. 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. 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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