结果中带有额外字段的 SQL UNION 查询
我有一个运行良好的 SQL 查询,只是我想将第一个数据库中另一列的结果带入其中。这就是我目前拥有的:
SELECT parts1.PART_NBR, parts1.NIIN
FROM parts1
WHERE parts1.PART_NBR='$pn'
UNION
SELECT parts2.REFERENCE_NUMBER, parts2.NIIN
FROM parts2
WHERE parts2.REFERENCE_NUMBER='$pn'
这就是我基本上想要的(当然这不会工作):
SELECT parts1.PART_NBR, parts1.NIIN, parts1.ANOTHER_FIELD
FROM parts1
WHERE parts1.PART_NBR='$pn'
UNION
SELECT parts2.REFERENCE_NUMBER, parts2.NIIN
FROM parts2
WHERE parts2.REFERENCE_NUMBER='$pn'
如何编写查询,以便它执行相同的操作,但实际上会带回结果中的额外字段?
I have a SQL query that is working well except I would like to bring the results of another column in the first db with it. This is what I currently have:
SELECT parts1.PART_NBR, parts1.NIIN
FROM parts1
WHERE parts1.PART_NBR='$pn'
UNION
SELECT parts2.REFERENCE_NUMBER, parts2.NIIN
FROM parts2
WHERE parts2.REFERENCE_NUMBER='$pn'
This is what I basically want (of course this wont work):
SELECT parts1.PART_NBR, parts1.NIIN, parts1.ANOTHER_FIELD
FROM parts1
WHERE parts1.PART_NBR='$pn'
UNION
SELECT parts2.REFERENCE_NUMBER, parts2.NIIN
FROM parts2
WHERE parts2.REFERENCE_NUMBER='$pn'
How do I write the query so that it does the same thing but actually brings back the extra field in the results?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
创建一个空字段,返回 NULL
编辑:
从您的评论中,您看到的结果为
第一个结果来自表
parts1
,第二个结果来自parts2
,空白的Name
字段位于其中您正在返回NULL
。从您提供的信息中,我不明白您为什么使用
UNION
来获取这两个表的结果,因为它们似乎包含相同的信息,除了第一个表也有名称
字段。JOIN
零件/参考编号上的表格以便选择名称不是更好吗?编辑:
正如您在评论中所说,之前由于使用
UNION
,您获得了DISTINCT
结果集。使用NULL
字段,行不再是唯一的,查询将返回所有行。我在评论中说,我看不到当前的 UNION 语句为您做了什么,因为两个表似乎都有相同的信息。这个询问是否比您告诉我们的更多?
Create an empty field, returning NULL
EDIT:
From your comment you are seeing the results as
The first results are coming from the table
parts1
the second fromparts2
, the blankName
fields are where you are returningNULL
.From the information you have given I don't see why you are using a
UNION
to get the results from these two tables as they seem to contain the same information except the first table also has theName
field.Would it not be better to
JOIN
the tables on the Part/Reference number in order to select the name?EDIT:
As you said in your comment, previously you were getting a
DISTINCT
result set because of usingUNION
. With theNULL
field the rows are no longer unique and the query returns all the rows.I said in a comment that I do not see what the current UNION statement is doing for you as it seems the same information is both tables. Is there more to this query than what you have told us?
您必须有匹配的列,但是您可以在返回
null
或任何您想要的默认值的第二个列中放置一个“假”列。You have to have matching columns, however you can place a "fake" column in the second one that comes back
null
or whatever default value you want.简单如下:
您只需在第二个查询中容纳一个占位符以匹配第一个查询的额外字段位置。
Simple as below:
You just need to accommodate a placeholder in the second query to match the extra field location of the first.