mysql - SQL Left Join via foreign keys, how to avoid duplicate columns?
问题描述
I have numerous tables I join with a primary key field. I can query with the below to get the results I need.
Select *
from orders
Left Join serviceorders on orders.contractLineID = serviceorders.lineID
Left Join all_orders on orders.OrderNum = all_orders.ordernum
Left Join invoices on orders.OrderNum = invoices.OrderNum
Left Join schedule on orders.OrderNum = schedule.Ordernum;
But when I try to create a view from this, I face duplicate columns, as each table I'm joining has the ordernum in it.
I know I shouldn't use * to select everything, but I don't know the syntax for selecting columns from multiple tables?
Is it just:
SELECT orders.column1, orders.column2 schedule.column1, schedule.column 2, invoice.column1, invoice.column2
FROM orders, schedule, invoice
I've also seen you can use the USING command, but the syntax for that is unclear. I'm not sure if that would be the better option as it's just the one column that's being repeated across all tables.
解决方案
这是语法:
SELECT TableA.id AS tableA_id, -- Or anything you want to name it after 'AS'
TableB.id AS tableB_id
FROM TableA
INNER
JOIN TableB
ON TableA.key = TableB.key
这是如果您需要视图具有两个 id,并具有不同的名称。更好的是只选择您想要的列。
推荐阅读
- hyperledger-fabric - Hyperledger Composer - 部署到多组织结构
- jquery - (Jquery、Ajax、Django、Cors、GET)没有“Access-Control-Allow-Origin”标头 - 忽略 Cors 白名单
- gremlin - TinkerPop: Gremlin revisiting visited edges
- javascript - Thinger.IO response timestamp (1486047553711) string to Date time
- python - macOS 上 VS Code 上的 Python 路径
- regex - Extracting 5 fields from logfile containing a string in Splunk
- ios - 核心数据和解码:在 json 中更进一步的层次结构
- jasper-reports - 条形图未显示所有类别 Jaspersoft Studio
- elasticsearch - match_phrase elasticsearch 中的可选术语
- sql - SQL Server CTE 语句中的错误