Mysql SQL将多列连接为一列
两张表:Mysql SQL将多列连接为一列,mysql,sql,Mysql,Sql,两张表: airline(a_code, name); serves(a_code, from_code, to_code) 我只想生成两列,列出航空公司提供的所有航班(名称、航班代码) 应该是这样的 SELECT a_code,from_code as flight_code from airline NATURAL JOIN serves UNION SELECT a_code,to_code as flight_code from airline NATURAL JOIN serves
airline(a_code, name);
serves(a_code, from_code, to_code)
我只想生成两列,列出航空公司提供的所有航班(名称、航班代码)
应该是这样的
SELECT a_code,from_code as flight_code from airline NATURAL JOIN serves
UNION
SELECT a_code,to_code as flight_code from airline NATURAL JOIN serves
直觉告诉我应该有更有效的查询。
也许像
SELECT name, **flight_code**
FROM airline JOIN serves
ON a_code = from_code **as_flight_code** OR a_code = to_code **as_flight_code_as_well**
但不确定如何解决列名歧义(选择名称,a_code是否在这里起作用?首先,不要使用
自然连接。这只会使您的代码容易出错,因为您可能不知道哪些列用于连接
事实上,您根本不需要加入
:
select s.a_code, from_code as flight_code
from serves s
where s.a_code = $a_code
union
select s.a_code, to_code
from serves s
where s.a_code = $a_code;
否则,您的查询就可以了。如果您知道from_code
和to_code
从来都不一样,那么在一个_code in(from_code,to_code)
上使用union all
而不是union