NOT IN和SQL连接

时间:2016-07-11 16:17:12

标签: sql-server join notin

我编写了一个SQL语句,其中这些特定列来自表,它与另一个表连接,主键ReportID作为两个表之间的链接。我使用NOT IN来准确显示公司的报告,但是当选择公司时我没有输出。查询中是否有任何地方需要重新排列?

    valsql1 = "SELECT DISTINCT c.ReportID, c.COMPANYID, rl.REPORTNAME 
                FROM  CompanyReportListTable c 
                right join ReportList rl  on c.reportid = rl.ReportID 
                WHERE c.reportid  NOT IN(Select rl.ReportID FROM ReportList rl) 
                and rl.ReportVisible = 1 
                and CompanyID = " & DropDownList1.SelectedValue

3 个答案:

答案 0 :(得分:1)

我认为您不想排除所有报告。很难猜到两个不同表的目的,但我相信你只需要修改你试图排除的报告列表。 (在另一个答案中,您指的是"未经检查的报告,或空值"。)

SELECT ReportID, COMPANYID, REPORTNAME 
FROM CompanyReportListTable c
WHERE
    ReportID NOT IN
        (
        SELECT rl.ReportID FROM ReportList rl
        WHERE ... /* which reports are you trying to exclude? */
        ) 
    AND ReportVisible = 1 AND CompanyID = ?

答案 1 :(得分:0)

NOT IN它不需要它,为什么你使用in如果你只是在连接上使用它,没有它的好处,唯一的方法就是你必须选择同一个表的其他记录(当你使用像树结构这样的东西),你要做的就是所有结果都是零记录。

我想你只是想要这样的东西:

catch

内部联接看起来像这样:

valsql1 = "SELECT DISTINCT c.ReportID, c.COMPANYID, rl.REPORTNAME 
   FROM  CompanyReportListTable c 
         right join ReportList rl  on c.reportid = rl.ReportID 
   WHERE rl.ReportVisible = 1 
         and CompanyID = " & DropDownList1.SelectedValue

左连接的最后一个例子:

valsql1 = "SELECT DISTINCT c.ReportID, c.COMPANYID, rl.REPORTNAME 
   FROM  CompanyReportListTable c 
         inner join ReportList rl  on c.reportid = rl.ReportID 
   WHERE rl.ReportVisible = 1 
         and CompanyID = " & DropDownList1.SelectedValue

答案 2 :(得分:0)

So here's what I did to solve this problem: remove the DISTINCT keyword, keep the right join for the two tables. Have the reportvisible set to 1. Once a company is selected from the dropdownlist, the reportID under ReportList table, rl, not by using NOT IN, but by using IN, select the ReportID from table 2, ReportList, and keep it visible and order by it's name for clarity. By keeping it in, it will accurately display the results for each company, but this time, un-check the ones un-associated per company. So regardless of the number of reports per company, it will display the ones associated with it. Here's the correct query

valsql1 = "SELECT c.ReportID, c.COMPANYID, rl.REPORTNAME 
FROM  CompanyReportListTable c 
right  join  ReportList rl on c.reportid = rl.ReportID and reportvisible = 1 and CompanyID =" & DropDownList1.SelectedValue & " 
where rl.ReportID IN (Select ReportID from ReportList where ReportVisible = 1) 
order by ReportName"