【问题标题】:mysql query ask 2nd table only if !=""mysql 查询仅在 !="" 时询问第二个表
【发布时间】:2014-09-27 11:43:17
【问题描述】:

我有一张顾客桌:

id, firstname, lastname, companyname,title_id,salutation_id
1,Peter,Pan,1,1
2,Cindy,Crawfort,Tinysoft,0,1
3,,,Amaton,,,
..

还有一个表格标题

id, name
1. Dr.
2. Dr. Prof.
...

和餐桌问候

id name
1, Mrs.
2,Mr.
3,none

我想做的是,做一个查询,如果它不为空,它会给我正确的称呼。 我试过了:

select *
from customers
 where if(customer.name!="",customer.title_id=titles.id) and   
       if(customer.name!="",customer.salutation_id=salutations.id) ;

这意味着如果存在,标题中的名称应该是正确的。但有时,像亚马逊一样,你没有名字,只有公司的名字。在这种情况下,公司的名称应该只被拿出来。

输出应如下所示: 彼得潘先生 亲爱的彼得潘博士或

夫人。克劳福特 亲爱的克劳福特夫人

或 亚马逊 亲爱的先生或女士们,

提到的查询是空的。任何的想法?谢谢! 海啸

【问题讨论】:

    标签: php mysql sql


    【解决方案1】:

    您需要在select 子句中使用left join 和一些逻辑:

    select c.*,
           (case when s.id is not null and s.id <> '' then s.name
                 else t.name
            end) as CorrectSalutation
    from customers c left join
         title t
         on c.title_id = t.id left join
         salutation s
         on c.salutation_id = s.id;
    

    【讨论】:

      猜你喜欢
      • 2015-02-09
      • 2013-07-16
      • 1970-01-01
      • 1970-01-01
      • 2016-08-02
      • 1970-01-01
      • 2013-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多