而不是一个子选择,对子查询使用一个INNER JOIN
。这将消除 NULL。
SELECT contacts.first_name,
contacts.last_name,
quote_id AS first_quote
FROM
contacts
INNER JOIN (
SELECT quotes.id, quotes_contacts.contact_id
FROM
quotes
LEFT JOIN quotes_contacts ON quotes.id = quotes_contacts.quote_id
JOIN (
SELECT quotes_contacts.contact_id, MIN(quotes.date_entered) AS date_entered
FROM
quotes
JOIN quotes_contacts ON quotes.id = quotes_contacts.quote_id
GROUP BY contact_id
) minquote ON quotes.date_entered = minquote.date_entered AND qc.contact_id = minquote.contact_id
) firstquote ON contacts.id = firstquote.contact_id
如果您确定quote.id
是递增的,并且最低的quote.id
percontact_id
也具有最早的,这可能会更简单date_entered
。在这种情况下,你可以做一个MIN(quote.id)
SELECT contacts.first_name,
contacts.last_name,
quote_id AS first_quote
FROM
contacts
INNER JOIN (
SELECT MIN(quotes.id) AS quote_id, quotes_contacts.contact_id
FROM quotes
LEFT JOIN quotes_contacts ON quotes.id = quotes_contacts.quote_id
GROUP BY contact_id
)minq ON contacts.id = minq.contact_id