SQL将多个列连接成一个

时间:2015-12-13 02:57:21

标签: 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

Intuition告诉我应该有更高效的查询。 也许像是

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

但不确定如何解决列名歧义(SELECT名称, a_code 会在这里工作吗?)

1 个答案:

答案 0 :(得分:0)

首先,不要使用join。它只会使您的代码容易出错,因为您可能没有意识到哪些列用于join

事实上,您根本不需要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_codeunion all永远不会相同,那么请使用union代替using System.Data.Linq; using Mono.Data.Sqlite; var connectionString = "Data Source=" + filePath + ";DbLinqProvider=SQLite;Version=3;"; var connection = new SqliteConnection(connectionString); var context = new DataContext(connection); foreach (Output output in context.GetTable<Output>()) { UnityEngine.Debug.Log(output.ID); }