带有保存状态的IF语句中的SELECT与SELECT

时间:2019-05-29 23:12:19

标签: mysql

我试图找到一些避免第三次SELECT的解决方案,但我什至不知道谷歌是怎么做到的。

我的尝试(可以工作,但看上去很丑):

SELECT
    u.*,
    IF(
        (SELECT meta_value from usermeta WHERE user_id = u.ID AND meta_key = 'first_name') = '',
        'John',
        (SELECT meta_value from usermeta WHERE user_id = u.ID AND meta_key = 'first_name')
    ) as first_name,
    (SELECT meta_value from usermeta WHERE user_id = u.ID AND meta_key = 'reputation') as reputation
FROM wp_users AS u

我想要这样的东西:

SELECT
    u.*,
    IF(
        (SELECT meta_value from usermeta WHERE user_id = u.ID AND meta_key = 'first_name') = '',
        'John',
        SOME_STATE0
    ) as first_name,
    (SELECT meta_value from usermeta WHERE user_id = u.ID AND meta_key = 'reputation') as reputation
FROM wp_users AS u

1 个答案:

答案 0 :(得分:0)

加入表而不是使用子查询。

SELECT u.*, IF(meta_value = '' OR meta_value IS NULL, 'John', meta_value) AS first_name
FROM wp_users AS u
LEFT JOIN usermeta AS m ON m.user_id = u.id AND m.meta_key = 'first_name'