使用连接从2个表中选择2列

时间:2018-04-30 10:57:20

标签: sql sql-server sql-server-2008

我有2个表,Table1有一个名为book names的列和许多其他列,而table table 2只有2列 - 所有书名和没有页面。 Table1中使用的书名数小于table2。没有id列,因此必须通过书名加入。 表2中列出的所有书籍都没有在表1中使用,它有一个较小的子集。 我在尝试着 选择table1.book name,table2.noOfPages 来自表1 书名的内部联接

虽然表1中只有100000行,table2中只有7000行,但查询返回200000行!我希望结果与table.1中的行数相匹配 不确定我做错了什么? 有人可以帮忙吗? 谢谢 苏西

4 个答案:

答案 0 :(得分:1)

你需要select t1.bookname, t2.noOfPages from table1 t1 left join table2 t2 on t1.bookname = t2.bookname; ,例如:

table1

如果table2中存在重复项,您可能会获得更多结果而不是select t2.bookname from table2 t2 group by t2.bookname having count(*) > 1; 。你可以这样做:

;WITH Rankings AS
(
    -- Your query here
    SELECT
        CountryCode = 1,
        ClientRef = 1,
        QuoteDate = 1,
        PRank = 1
),
Only1Record AS
(
    SELECT
        R.CountryCode, 
        R.ClientRef, 
        R.QuoteDate
    FROM
        Rankings AS R
    GROUP BY
        R.CountryCode, 
        R.ClientRef, 
        R.QuoteDate
    HAVING
        MAX(R.PRank) = 1
)
DELETE D FROM
    Only1Record AS R
    INNER JOIN Rankings AS D ON
        R.CountryCode = D.CountryCode AND
        R.ClientRef = D.ClientRef AND
        R.QuoteDate = D.QuoteDate

答案 1 :(得分:0)

MAX GROUP BY的一种方式是返回预期的输出而没有重复的值,但由于查询中的MAX,它可能返回错误的页数,因此如果它是&#39}。没问题,然后离开它,否则找到重复并纠正它

SELECT t1.bookname, t2.noOfPages
FROM (SELECT bookname, MAX(noOfPages) AS noOfPages 
      FROM table2
      GROUP BY bookname) t2  
INNER JOIN  table1 t1 ON t1.bookname = t2.bookname;

答案 2 :(得分:0)

Use an INNER JOIN to get the pairs only. ie. The union of A and B, where A is table1, and B is table2.

example. 

SELECT t1.BookName, t2.noOfPages 
FROM Table1 as t1 INNER JOIN Table2 as t2 on t1.BookName = t2.BookName

也许缺失的部分是关键链接,或者两个表中都有重复的名称,因为没有主键和外键,所以很难分辨。也许尝试使用DISTINCT:

SELECT DISTINCT t1.BookName, t2.noOfPages 
FROM Table1 as t1 INNER JOIN Table2 as t2 on t1.BookName = t2.BookName

答案 3 :(得分:0)

select t1.bookname, t2.noOfPages
from table1 t1 left join
     table2 t2
     on t1.bookname = t2.bookname
-- and t1.bookname like '%martin%' -- do not filter here
where t1.bookname like '%martin%'; -- filter conditions ALWAYS in where

永远不要在join条件下过滤您的数据。这很慢。在where - 部分中添加过滤器。这样就可以在db连接表之前减少数据。