如果条件使用另一个WHERE与else相遇,则使用WHERE

时间:2016-08-03 00:04:36

标签: sql

我的例子在这里:

Select T1.*,
       TC.country_name,
       TS.state_name,
       T1.address_type
From mtpd2_virtuemart_order_userinfos T1
     Left Join mtpd2_virtuemart_countries TC On TC.virtuemart_country_id = T1.virtuemart_country_id
     Left Join mtpd2_virtuemart_states TS On TS.virtuemart_state_id = T1.virtuemart_state_id
Where T1.address_type ='ST' OR T1.address_type = 'BT'
      And T1.virtuemart_order_id /*SELECTED_ID_LIST*/

我正在寻找的逻辑是使用(WHERE T1.address_type='ST'),如果单元格内的字符串是' ST'否则使用(WHERE T1.address_type='BT')

enter image description here

3 个答案:

答案 0 :(得分:0)

只需使用parantheses并否定第二个子句中的ST部分:

Select T1.*,
   TC.country_name,
   TS.state_name,
   T1.address_type
From mtpd2_virtuemart_order_userinfos T1
    Left Join mtpd2_virtuemart_countries TC On TC.virtuemart_country_id = T1.virtuemart_country_id
     Left Join mtpd2_virtuemart_states TS On TS.virtuemart_state_id =     T1.virtuemart_state_id
Where 
     (T1.address_type ='ST' OR (T1.address_type <>'ST' && T1.address_type = 'BT'))
And T1.virtuemart_order_id /*SELECTED_ID_LIST*/

答案 1 :(得分:0)

用括号括起你的OR语句应该足以满足你的需要。

WHERE (T1.address_type ='ST' OR T1.address_type = 'BT')
AND T1.virtuemart_order_id 

答案 2 :(得分:0)

这可以解决问题,但我不确定这是否是最佳方式: 1.创建一个只有address_type ='ST'作为tableA的表 2.创建另一个只有address_type ='BT'的表和tableA中不存在的customer_ids ---说这个表是tableB 追加(Concatenate / Union)两个表

此代码可用于此目的:

select * from
    (Select T1.*,
           TC.country_name,
           TS.state_name,
           T1.address_type
    From mtpd2_virtuemart_order_userinfos T1
         Left Join mtpd2_virtuemart_countries TC On TC.virtuemart_country_id = T1.virtuemart_country_id
         Left Join mtpd2_virtuemart_states TS On TS.virtuemart_state_id = T1.virtuemart_state_id
    Where T1.address_type ='ST'
          And T1.virtuemart_order_id /*SELECTED_ID_LIST*/) as A
    Union

select * from
    (Select T1.*,
           TC.country_name,
           TS.state_name,
           T1.address_type
    From mtpd2_virtuemart_order_userinfos T1
         Left Join mtpd2_virtuemart_countries TC On TC.virtuemart_country_id = T1.virtuemart_country_id
         Left Join mtpd2_virtuemart_states TS On TS.virtuemart_state_id = T1.virtuemart_state_id
    Where T1.address_type = 'BT'
          And T1.virtuemart_order_id /*SELECTED_ID_LIST*/
          And TS.state_id not in ( select TS.state_name
                                   From mtpd2_virtuemart_order_userinfos T1
                                   Left Join mtpd2_virtuemart_countries TC On                         TC.virtuemart_country_id = T1.virtuemart_country_id
         Left Join mtpd2_virtuemart_states TS On TS.virtuemart_state_id = T1.virtuemart_state_id
    Where T1.address_type ='ST'
          And T1.virtuemart_order_id /*SELECTED_ID_LIST*/ ) ) as B