选择主要或下一个最佳记录

时间:2014-04-14 16:53:14

标签: mysql sql

我有三张表格,其中包含有关联系人和地址的信息。

Contact
  id
  name
  dob
  etc...

Address
 line1
 line2
 postcode
 etc...

ContactAddress
  contact_id
  address_id
  primary

我正在尝试找出如何获取联系人列表和单个地址。此地址应该是可用的主要地址(主要设置为true),如果有可用的话,则为辅助地址,如果两者都不可用,则为空地数据。

显然,在ContactAddress上使用group by为每个联系人提供了一个地址,但我如何将这些地址标记优先为主要地址。

1 个答案:

答案 0 :(得分:0)

此查询应该可以解决问题......

SELECT c.Id, c.Name, c.DOB, a.Line1, a.Line2, a.Postcode
FROM Contact c
INNER JOIN ContactAddress ca ON c.Id = ca.Contact_Id
INNER JOIN [Address] a ON ca.Address_Id = a.Id
INNER JOIN
    (SELECT c.Id AS Contact_Id,
        (SELECT TOP 1 Address_Id FROM ContactAddress WHERE Contact_Id=c.Id ORDER BY [Primary] DESC) AS Address_Id
    FROM Contact c) x
ON ca.Contact_Id = x.Contact_Id and ca.Address_Id = x.Address_Id

UNION

SELECT c.Id, c.Name, c.DOB, null, null, null
FROM Contact c 
WHERE NOT EXISTS (SELECT * FROM ContactAddress WHERE Contact_Id=c.Id)