Question

I´m working with virtuemart, and I have a table that store all the information about the orders and the address of the users. When a user sign in they give me one address that I call 'BillTo' but when they make and order, the user can create a new address called 'shipto'. So If they create a new address 'shipto' I have to send the invoice to 'billto' and the items of the order to 'shipto'. I´m trying to get all the addresses to send the items of the orders. So I have the table like this

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

I need to get all the ST addresses, and if not exists get the BT address.

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

How can I do that?

EDIT:

This is my SQL query. SELECT o.order_number,os.order_status_name,ou.first_name,ou.last_name,ou.last_name2,ou.phone_1,ou.phone_2,ou.address_1,ou.address_2,ou.zip,ou.city,uv.fieldtitle

FROM #__virtuemart_product_campaigns AS pc

LEFT JOIN #__virtuemart_order_items AS oi ON (pc.virtuemart_product_id = oi.virtuemart_product_id)

LEFT JOIN #__virtuemart_orders AS o ON (oi.virtuemart_order_id = o.virtuemart_order_id)

LEFT JOIN #__virtuemart_orderstates AS os ON (os.order_status_code = o.order_status)

LEFT JOIN #__virtuemart_order_userinfos AS ou ON (ou.virtuemart_order_id = o.virtuemart_order_id)

LEFT JOIN #__virtuemart_userfield_values AS uv ON (uv.fieldvalue = ou.provincia)

WHERE (o.order_status = 'U' OR o.order_status = 'C' OR o.order_status = 'S') AND pc.virtuemart_campaign_id = '133' AND ou.address_type = 'ST' ORDER BY o.virtuemart_order_id ASC

Now, y remove from the query "AND ou.address_type = 'ST'" and delete the duplicates from the result with a foreach, but I would like to do it all in the same query

Was it helpful?

Solution

One method is if 'Type' is 'ST' include it OR if your table has a unique row (e.g for id 2 in your case) then also include it.

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 )

Though it has nested query but will be easy to implement considering you don't have too much data.

OTHER TIPS

Here is another way to get your desired output by using SUBSTRING_INDEX over 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

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top