简体   繁体   中英

Adding Multiple Columns from Multiple Tables to One column in a Query MYSQL

So just like the title says, I am trying to combine tables that have similar columns in a query. The result should be that i would have Division, Brigade, Regiment where regiment as 2 tables that can populate it. But i am having trouble combining the two table's columns to make that one column in the query. This is what i have tried:

SELECT d.name Division 
     , b.name Brigade
     , r.name Regiment
     , s.name Regiment
     , d.CO
     , b.FOB
     , r.Combatants 
  FROM ArmyDivision d
     , ArmyBrigade b
     , ArmyRegiment r
     , ArmySpecRegiment s 
 WHERE b.CO  = d.CO 
   AND b.FOB = r.FOB 
   AND d.CO  = s.CO

So r.name and s.name should be in the same column in the query under Regiment. I know this is wrong and it was a long shot. I have tried different variants of this but nothing, and google isnt very helpful as it is showing how to add columns from one table to another (not what i wanted). So basically, how would i do this efficiently?

Also, the data in AmrySpecRegiment does not have a brigade, just a division, so im assuming Brigade would be null for those entries. i dont know if this makes a different on how to do this query, but i figured might as well let you know.

SELECT d.name as Division, b.name as Brigade,r.name as Regiment,s.name as Regiment, d.CO, b.FOB, r.Combatants 
FROM ArmyDivision d 
INNER JOIN (ArmyBrigade b 
INNER JOIN ArmyRegiment r
ON b.FOB=r.FOB)
ON b.CO=d.CO
INNER JOIN ArmySpecRegiment s
ON d.CO = s.CO

INNER could be changed to LEFT if necessary

Also, to have multiple fields in one column, use CONCAT.

Are you trying to get the concatenated result of r.name and s.name column. In that case, you can use CONCAT() function like below. Also, notice that I have changed your old style implicit join syntax to ANSI92 style explicit join syntax.

select d.name as Division, 
b.name as Brigade,
CONCAT(r.name, ' ', s.name) as Regiment, 
d.CO, 
b.FOB, 
r.Combatants 
from ArmyDivision d 
join ArmyBrigade b on b.CO=d.CO
join ArmyRegiment r on b.FOB=r.FOB
join ArmySpecRegiment s on d.CO=s.CO; 

Both columns you have extracted as "Regiment". As far as I know, you can't do this if you use the same name. If you use something like "r.name as Regiment_1,s.name as Regiment_2," That will bring the values to two columns.

When you say, you want both columns in one column, eg: We may have first_name and last_name in two columns. And now you want to get both column values to one column to display the whole name,

that can be done by this > SELECT CONCAT(first_name, ' ', last_name) AS FullName;

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