即使一个条件为假,也要获取值

时间:2012-11-11 00:57:19

标签: sql where exists

这是我的实际查询:

SELECT temp.id_company AS id_company
     , temp.code_product AS id_product
     , temp.date_product  AS date_p
FROM (
   SELECT *
   FROM companies 
   INNER JOIN products
      ON products.id_company_product = companies.id_company
   WHERE module_key_company = "daL/RqzZcfqc."
   ) AS temp
WHERE temp.code_product = "app_12"

首先我得到companies.id_company where companies.module_key_company匹配“dal .....”然后我检查我是否得到了products.code_product = "app_12"products.id_company = companies.id_company在第一次测试后得到的匹配。

如果两个条件都成立,我得到我想要的。但是如果products.code_product没有匹配,我也想获得companies.id_company。

即使module_key错误,我也无法找到如何通过code_product测试获取id_company。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT companies.id_company
     , coalese(products.code_product,'NONE') as id_product
     , products.date_product as date_p
FROM companies 
LEFT OUTER JOIN products
   ON     products.id_company_product = companies.id_company
      and products.code_product = 'app_12'

WHERE companies.module_key_company = 'daL/RqzZcfqc.'

对于没有任何匹配产品的公司,id_product列将包含 NONE 文本,date_p列将 null 。此外,您应该使用单引号来提供字符常量,而不是双引号。

答案 1 :(得分:0)

很难说出你的表结构是什么,除非你用表名后缀列名。这就是我猜的。试试这个:

SELECT C.id_company, P.code_product, P.date_product
  FROM Companies AS C
    LEFT OUTER JOIN Products AS P ON P.id_company_product = C.id_company
  WHERE module_key_company = 'daL/RqzZcfqc.'
    AND (P.code_product = 'app_12' OR P.code_product is NULL) 

最佳, 乔