1

i have table users with id,name,type,active,...

i have another table orders with orderid,userid,...

i want to update orders table in such a way that

UPDATE orders SET userid=(SELECT id FROM users WHERE type="some" and active=1)

but my problem is if SELECT id FROM users WHERE type="some" and active=1 doesnt have any result i want to use SELECT id FROM users WHERE type="some" limit 0,1

ie the first result

i can do this easly in any language like php/python etc but i just have access to mysql server so cannot do that

but how can i do in pure sql in single query

i tried if statement but not working

1
  • 1
    SELECT id FROM users WHERE type="some" order by active <> 1 limit 1 Commented Nov 4, 2019 at 12:36

1 Answer 1

1

Here is one method using ORDER BY:

UPDATE orders o
    SET userid = (SELECT u.id
                  FROM users u
                  WHERE u.type = 'some'
                  ORDER BY active DESC
                  LIMIT 1
                 );

This assumes that active only takes on the values 0 and 1. If there are other values, use ORDER BY (active = 1) DESC.

Performance should be fine with an index on users(type, active, id).

Another method uses aggregation and COALESCE():

UPDATE orders o
    SET userid = (SELECT COALESCE(MAX(CASE WHEN active = 1 THEN u.id END),
                                  MAX(u.id)
                                 )
                  FROM users u
                  WHERE u.type = 'some'
                 );

I would expect the ORDER BY to be a wee bit faster, but sometimes MySQL surprises me with aggregations in correlated subqueries. That said, if you have very few rows for a given type, the performance difference may not be noticeable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.