MySQL查询条件OR

时间:2014-05-01 09:53:33

标签: mysql conditional-statements

我正在使用virtuemart,我有一个表存储有关订单和用户地址的所有信息。当用户登录时,他们会给我一个我称之为“BillTo”的地址,但是当他们制作和订购时,用户可以创建一个名为“shipto”的新地址。因此,如果他们创建一个新的地址'shipto',我必须将发票发送到'billto',并将订单的项目发送到'shipto'。我试图获取所有地址以发送订单的项目。所以我有这样的表

ORDER_ID   |   TYPE   |   ADDRESS
----------------------------------
1           BT           My office
1           ST           My house
2           BT           Home home home
3           BT            office
3           ST           office 2

我需要获取所有ST地址,如果不存在则获取BT地址。

1           ST           My house
2           BT           Home home home
3           ST           office 2

我该怎么做?

编辑:

这是我的SQL查询。 选择oorder_numberosorder_status_nameoufirst_nameoulast_name,{ {1}}。oulast_name2ouphone_1ouphone_2ou,{{1 }。{。{1}},address_1ouaddress_2ouzipou

FROM city AS uv

LEFT JOIN fieldtitle AS #__virtuemart_product_campaigns ON(pc#__virtuemart_order_items = oipc

LEFT JOIN virtuemart_product_id AS oi ON(virtuemart_product_id#__virtuemart_orders = ooi

LEFT JOIN virtuemart_order_id AS o ON(virtuemart_order_id#__virtuemart_orderstates = osos

LEFT JOIN order_status_code AS o ON(order_status#__virtuemart_order_userinfos = ouou

LEFT JOIN virtuemart_order_id AS o ON(virtuemart_order_id#__virtuemart_userfield_values = uvuv

WHERE(fieldvalueou ='U'或provinciao ='C'或order_statuso =' S')和order_statuso ='133'和order_statuspc ='ST'ORDER BY o.virtuemart_order_id ASC

现在,从查询中删除“AND virtuemart_campaign_idou ='ST'”并使用foreach从结果中删除重复项,但我想在同一个项目中删除查询

3 个答案:

答案 0 :(得分:2)

以下是使用SUBSTRING_INDEX超过GROUP_CONCAT

获取所需输出的另一种方法
SELECT ORDER_ID
,SUBSTRING_INDEX(GROUP_CONCAT(`TYPE` ORDER BY `TYPE` DESC),',',1) `TYPE` 
,SUBSTRING_INDEX(GROUP_CONCAT(`ADDRESS` ORDER BY `TYPE` DESC),',',1) `ADDRESS` 
FROM t
GROUP BY ORDER_ID 

Fiddle Demo

答案 1 :(得分:2)

一种方法是,如果'Type'是'ST'包含它,或者如果你的表有一个唯一的行(例如你的情况下为id 2),那么也包括它。

SELECT * FROM table1 t1 
WHERE t1.TYPE='ST' OR
t1.ORDER_ID IN (select ORDER_ID from table1 group by ORDER_ID having  count(*)=1 )

虽然它有嵌套查询但考虑到你没有太多数据会很容易实现。

答案 2 :(得分:0)

select t1.*
from your_table t1
join
(
  select order_id, max(type) as type
  from your_table
  group by order_id
) t2 on t1.order_id = t2.order_id and t1.type = t2.type