我不太清楚如何做到这一点:
SELECT contacts.first_name,
contacts.last_name,
(
SELECT quotes.id
FROM quotes
LEFT JOIN quotes_contacts ON quotes.id = quotes_contacts.quote_id
WHERE quotes.id IS NOT NULL
AND quotes_contacts.contact_id = contacts.id
ORDER BY quotes.date_entered
LIMIT 1
) AS 'first_quote'
FROM
contacts
但是,first_quote
返回的某些值将作为null
返回。我怎么能阻止它?
答案 0 :(得分:1)
而不是子选择,对子查询使用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
每contact_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
{{1}}
答案 1 :(得分:0)
如果subselect找到一行并且id
的值为null,则您的WHERE
子句会阻止它返回。但是,只要subselect根本找不到任何内容,first_quote
的值仍然为null。外面的额外警卫应该可以做到这一点:
SELECT contacts.first_name,
contacts.last_name,
(
SELECT quotes.id
FROM quotes
LEFT JOIN quotes_contacts ON quotes.id = quotes_contacts.quote_id
WHERE quotes.id IS NOT NULL
AND quotes_contacts.contact_id = contacts.id
ORDER BY quotes.date_entered
LIMIT 1
) AS 'first_quote'
FROM contacts
WHERE first_quote IS NOT NULL
但是JOIN比这里的子选择更有效。