简体   繁体   English

SQL左外连接表

[英]SQL left outer join table

I'm trying to pull out 3 columns from two tables, and I seem to be having a little problem.我试图从两个表中拉出 3 列,但我似乎遇到了一些问题。

SELECT a.[CreatedFromIp], b.[Token],  b.[MaskedP]
from [dbo].[Users] a LEFT OUTER JOIN [dbo].[Cards] b ON a.[Id]= b.[Id]
WHERE CreatedFromIp IS NOT NULL
Order by Token

but I keep getting Error converting data type nvarchar to bigint.但我不断收到将数据类型 nvarchar 转换为 bigint 的错误。

If I turn the tables around, I get all the token and masked info, but the IP result is just a whole list of NULL values.如果我把表反过来,我会得到所有的令牌和掩码信息,但 IP 结果只是一个完整的 NULL 值列表。

You need to convert your both table id column to bigint - due to data type mismatch you are getting the error您需要将两个表 id 列转换为bigint - 由于数据类型不匹配,您收到错误

SELECT a.[CreatedFromIp], b.[Token],  b.[MaskedP]
from [dbo].[Users] a LEFT OUTER JOIN [dbo].[Cards] b 
ON cast(a.[Id] as bigint)= cast(b.[Id] as bigint)
WHERE CreatedFromIp IS NOT NULL
Order by Token

SQL Server automatically converts away from strings when there is a comparison. SQL Server自动从字符串时,有一个比较转换 The simple solution is to require that all columns that might be used in a join are of the same type.简单的解决方案是要求join中可能使用的所有列都属于同一类型。 In this case, a simple foreign key definition would have helped when setting up the data model.在这种情况下,在设置数据模型时,一个简单的foreign key定义会有所帮助。

You can remove the error by converting to strings:您可以通过转换为字符串来消除错误:

SELECT u.[CreatedFromIp], c.[Token], c.[MaskedP]
FROM [dbo].[Users] u LEFT OUTER JOIN
     [dbo].[Cards] c
      ON CONVERT(VARCHAR(255), u.[Id]) = CONVERT(VARCHAR(255), c.[Id])
WHERE CreatedFromIp IS NOT NULL
ORDER BY Token;

Of course, one of those type conversions is redundant, because the field is already a string.当然,其中一种类型转换是多余的,因为该字段已经是一个字符串。

Alternatively, you can convert the columns to integers -- using try_convert() or try_cast() :或者,您可以将列转换为整数——使用try_convert()try_cast()

SELECT u.[CreatedFromIp], c.[Token], c.[MaskedP]
FROM [dbo].[Users] u LEFT OUTER JOIN
     [dbo].[Cards] c
      ON TRY_CONVERT(int, u.[Id]) = TRY_CONVERT(int, c.[Id])
WHERE CreatedFromIp IS NOT NULL
ORDER BY Token;

Of course, the real solution is to fix the data model so the columns used in the JOIN s have the same type.当然,真正的解决方案是修复数据模型,使JOIN使用的列具有相同的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM