从两个表中选择数据

时间:2010-12-07 17:26:27

标签: sql sql-server-2008

我有两个表Accountdetails和帐户

  • Accountdetails由AD_ID,AD_Name,AD_AccNo
  • 列组成
  • 帐户包含列A_Name,A_AccNo,A_AccDate

我的问题是我想根据AD_AccNo和A_AccNo相等选择数据

我尝试使用此查询

select AD.AD_ID, a.A_Name, a.A_AccNo, a.A_AccDate 
from Accountdetails as AD, Accounts as a 
where AD.AD_AccNo = a.A_AccNo

有人能建议我出错的地方吗?

7 个答案:

答案 0 :(得分:1)

select AD.AD_ID, a.A_Name, a.A_AccNo, a.A_AccDate 
from Accountdetails AD left join Accounts a 
ON AD.AD_AccNo = a.A_AccNo

答案 1 :(得分:0)

尝试

SELECT AD.AD_ID, a.A_Name, a.A_AccNo, a.A_AccDate from Accountdetails AD
LEFT JOIN Accounts a ON AD.AD_AccNo=a.A_AccNo
WHERE .... [your criteria here]

答案 2 :(得分:0)

使用联接应该有效:

SELECT
    ad.AD_ID,
    a.A_Name,
    a.A_AccNo,
    a.A_AccDate
FROM
    Accountdetails ad
INNER JOIN
    Accounts a ON a.A_AccNo = ad.AccNo
WHERE
    [insert any conditional criteria here]    

答案 3 :(得分:0)

表格中必须有一些重复的帐号值。

如果Accountdetails中有3行,帐号为X,而Accounts中有4行具有相同的数字,则该联接会在结果集中添加12行。

要确定这一点,请尝试以下

select COUNT(*), AD_AccNo from Accountdetails GROUP BY AD_AccNo HAVING COUNT(*) > 1 

select COUNT(*), A_AccNo from Accounts GROUP BY A_AccNo HAVING COUNT(*) > 1

这个决议取决于他们为什么在那里。您需要加入其他列吗?

答案 4 :(得分:0)

SELECT R.roleID, R.rolename, P.DisplayName, P.canRead, P.canWrite, P.canDelete
FROM role R
INNER JOIN (SELECT rp.roleId, rp.canDelete, rp.canRead, rp.canWrite, rp.moduleId,
            tm.DisplayName, tm.IsActive, tm.ParentId, tm.url
            FROM rolesPermissions rp
            INNER JOIN tbl_be_Modules tm ON rp.moduleId = tm.Id) P ON R.roleID = P.roleId

答案 5 :(得分:-1)

SELECT ad.AD_ID,
       ad.AD_Name,
       ad.AD_AccNo,
       a.A_Name,
       a.A_AccNo,
       a.A_AccDate 
FROM Accountdetails ad
INNER JOIN Accounts a
ON ad.AD_AccNo = a.A_AccNo  

答案 6 :(得分:-2)

这是确切的查询,你不是在做一个小组或类似的事情?