3

我不太确定如何做到这一点:

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

但是返回 as 的一些值first_quote被返回为null. 我怎么能阻止它?

4

2 回答 2

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.idpercontact_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
于 2012-10-17T13:31:58.413 回答
0

如果子选择找到一行并且值为id空,则您的WHERE子句会阻止它被返回。但是每当子选择根本没有找到任何东西时, 的值first_quote仍然是空的。外面的额外警卫应该可以解决问题:

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 比子选择更有效。

于 2012-10-17T13:33:44.457 回答