I need some help on my mysql syntax.
My table has user information but has the same order number for both ship to and bill to.
Sometimes people choose to ship to their billing address; I only need the order number record where users didn’t enter a shipping addresses, and where they entered a shipping address.
If they entered both bill to and shipping addresses, I only need the shipping address, if that makes sense.
In the table there are sometimes duplicate fields for one order number. If that’s confusing take a look below:
------------SQL TABLE -----------
order_id | address_type | user_name | address
100 | billto | Homer Simposn | 123 Main St.
100 | shipto | Homer Simpson | 455 XYZ Ave.
101 | billto | Peter Griffin | 780 111th St.
102 | billto | Charles Xavier | 555 Bergen St.
102 | shipto | Jean Gray | 555 Bergen St.
I need the output to be:
100 - shipto - Homer Simposn - 455 XYZ Ave.
101 - billto - Peter Griffin - 780 111th St.
102 - shipto - Jean Gray - 555 Bergen St.
Here is my syntax which will only return “shipto” records.
SELECT * FROM order_info AS A WHERE A.address_type = 'shipto' AND
NOT EXISTS (SELECT B.address_type
from order_info AS B
where B.address_type = A.address_type
and B.address_type = 'billto')
I would like to do something like IF there is no shipto then return the billto, Is this possible to do all in sql syntax?
Thanks!
You could achieve this by finding the groupwise maximum for your row.
Specifically, you use the order as the ID, and find the “maximum” address type in a subquery (it will find
shiptoif it’s there, andbilltoif not), and use that result to connect to rows in the outer query.For example (using an inefficient correlated subquery):
The above link gives an example of converting that to a more efficient join.