括号中的选择不为空

时间:2012-10-17 13:28:55

标签: mysql

我不太清楚如何做到这一点:

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返回。我怎么能阻止它?

2 个答案:

答案 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.idcontact_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比这里的子选择更有效。