简体   繁体   English

Mysql 多个 select 语句在单个查询中使用 if 条件

[英]Mysql multiple select statements in single query with if condition

i have table users with id,name,type,active,...我有 id、name、type、active、...的表用户

i have another table orders with orderid,userid,...我有另一个带有 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但我的问题是如果SELECT id FROM users WHERE type="some" and active=1没有任何结果我想使用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我可以用任何语言(如 php/python 等)轻松做到这一点,但我只能访问 mysql 服务器,所以不能这样做

but how can i do in pure sql in single query但是我怎么能在单个查询中使用纯 sql

i tried if statement but not working我尝试了 if 语句但不工作

Here is one method using ORDER BY :这是使用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 .这假设active仅采用值01 If there are other values, use ORDER BY (active = 1) DESC .如果还有其他值,请使用ORDER BY (active = 1) DESC

Performance should be fine with an index on users(type, active, id) .使用users(type, active, id)上的索引,性能应该很好。

Another method uses aggregation and COALESCE() :另一种方法使用聚合和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.我希望ORDER BY会快一点,但有时 MySQL 会让我惊讶于相关子查询中的聚合。 That said, if you have very few rows for a given type, the performance difference may not be noticeable.也就是说,如果给定类型的行数很少,则性能差异可能不会很明显。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM