更新:
由于检索哪些地址簿条目对您无关紧要,因此此查询将获取具有最大值的条目address_book_id
:
SELECT c.customers_id,
c.customers_firstname,
c.customers_lastname,
ab.address_book_id,
ab.customers_id,
ab.entry_company,
ab.entry_firstname,
ab.entry_lastname,
ab.entry_street_address
FROM customers c LEFT JOIN
address_book ab ON c.customers_id=ab.customers_id AND
ab.address_book_id = (SELECT MAX(address_book_id)
FROM address_book
WHERE customers_id = c.customers_id)
ORDER BY c.customers_id;
理论上,您可以让客户没有关联的通讯录条目。LEFT JOIN
将允许您拉动它们。如果您不想要这种行为,只需更改LEFT JOIN
为INNER JOIN
.
这是工作的sqlfiddle
原始答案
这是我的第一个答案,它可以在 MySql 中工作,尽管它可以从不同的行中获取任意值。请参阅@Gordon Linoff 的回答中的解释。
SELECT c.customers_id,
c.customers_firstname,
c.customers_lastname,
MAX(ab.address_book_id),
MAX(ab.customers_id),
MAX(ab.entry_company),
MAX(ab.entry_firstname),
MAX(ab.entry_lastname),
MAX(ab.entry_street_address)
FROM customers c INNER JOIN
address_book ON c.customers_id=ab.customers_id
GROUP BY c.customers_id, c.customers_firstname, c.customers_lastname,
ORDER BY c.customers_id