简体   繁体   English

T-SQL:检查表中是否存在数据

[英]T-SQL : check if data exists in table

I am using a view that checks if data exists in another table and if it exists if shows the number of row's connected to that table. 我正在使用一个视图,该视图检查另一个表中是否存在数据,以及是否显示连接到该表的行数。 Now I was wondering if there might be a faster way of doing this, since I am only interested if there is data and not necessary how many data rows there are. 现在,我想知道是否可能有一种更快的方法,因为我只对是否有数据感兴趣,而不必关心有多少数据行。 I guess when it does not need to count it will be faster. 我猜想它不需要计数时会更快。

This is what I use now: 这是我现在使用的:

SELECT
    dbo.user.id,
    dbo.user.userCode,
    COALESCE (TotalProducts.ProductsInback, 0) AS ProductsInback
FROM 
    dbo.user
LEFT OUTER JOIN
    (SELECT COUNT(id_product) AS ProductsInback, userCode
     FROM dbo.Product
     GROUP BY userCode) AS TotalProducts ON dbo.Product.userCode = TotalProducts.userCode
WHERE 
    dbo.user.userCode = 'XYZ' 

Now this works all fine an it gives me the number of products connected to the user XYZ that are in the back of the store. 现在一切正常,这给了我商店背面与用户XYZ连接的产品数量。 However I just want to know if the user has products in the back of the store, I don't need to know how many. 但是,我只想知道用户在商店后面是否有产品,我不需要知道有多少种。 That seems to me a faster solution (walking anyway to the back of the store). 在我看来,这是一个更快的解决方案(无论如何都要走到商店的后面)。 So replacing the COUNT with ... ? 那么用...替换COUNT吗?

You are right, for a lookup whether data exists in another table, we use EXISTS or IN , because we don't have to go through all matching rows then, but can stop at the first one found. 没错,对于查找数据是否存在于另一个表中的问题,我们使用EXISTSIN ,因为那时我们不必遍历所有匹配的行,但是可以在找到的第一个行处停止。

EXISTS : EXISTS

SELECT
  id,
  userCode,
  CASE WHEN EXISTS (SELECT * FROM dbo.Product p WHERE p.userCode = u.userCode )
       THEN 1 ELSE 0 END AS ProductsInback
FROM dbo.user u
WHERE u.userCode = 'XYZ' 

IN : IN

SELECT
  id,
  userCode,
  CASE WHEN userCode IN (SELECT userCode FROM dbo.Product)
       THEN 1 ELSE 0 END AS ProductsInback
FROM dbo.user
WHERE userCode = 'XYZ' 

If you change your left join to an inner join, you will just get a list of users with products. 如果将左联接更改为内部联接,则只会获得具有产品的用户列表。 The other users will not appear on the list. 其他用户将不会出现在列表中。

SELECT
dbo.user.id,
dbo.user.userCode

FROM dbo.user

JOIN dbo.Product
  ON dbo.Product.userCode= TotalProducts.userCode

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

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