SQL Query有两个表

时间:2014-10-09 17:17:51

标签: sql sql-server

我有两张表格如下

Point:                       ListMember:
index   description          indexParent     indexChild
--------------------         ---------------------------
1       ABC                  333             1
2       DEF                  333             2
3       GHI                  444             1
333     Hello                444             2
444     Bye                  444             3
555     Welcome      

我正在寻找的结果表的一个例子

Result:
Index     description        listSize    descriptionChild
333       Hello                2           ABC
333       Hello                2           DEF 
444       Bye                  3           ABC
444       Bye                  3           DEF
444       Bye                  3           GHI
555       Welcome              0           

我是数据库的新手,还在学习SQL,所以我不太确定如何选择以获得我想要的结果。

3 个答案:

答案 0 :(得分:0)

我确实认为以下查询适合您(SQL Fiddle):

SELECT p1.[index], p1.description, 
  (
    SELECT COUNT(1) 
    FROM ListMember ls
    WHERE ls.indexParent = p1.[index]
  ) AS listSize,
  p2.description AS descriptionChild
FROM Point p1
LEFT JOIN ListMember l ON l.indexParent = p1.[index]
LEFT JOIN Point p2 ON l.indexChild = p2.[index]
WHERE p1.[index] NOT IN 
(
  SELECT indexChild FROM ListMember
)

答案 1 :(得分:0)

假设你的结果应该是333 Hello。你必须做两个左连接(555没有孩子)。

psuedo代码:

Select p.index, p.description, p2.index as listsize, p2.description as descriptionchild
  from point p
  left join listmember l
    on p.index = l.indexparent
  left join point p2
    on l.indexchild = p2.index

答案 2 :(得分:0)

由于使用了不幸的列名index,每次引用该列时都必须包含括号。这对我有用:

SELECT P.[index] AS [Index],
    P.description,
    (SELECT COUNT(*) FROM ListMember WHERE indexParent = P.[index]) AS listSize,
    P2.description AS descriptionChild
FROM Point P
LEFT JOIN ListMember LM ON LM.indexParent = P.[index]
LEFT JOIN Point P2 ON P2.[index] = LM.indexChild
WHERE P.[index] NOT IN (SELECT indexChild FROM ListMember)
ORDER BY P.[index]