子查询以查看单独表中的字段对于相同的ID是空还是空

时间:2015-07-27 14:26:11

标签: php mysql sql wordpress

我这样得到了作者:

$feat_authors = $wpdb->get_results("SELECT ID, user_nicename from $wpdb->users WHERE display_name <> 'admin' ORDER BY rand() LIMIT 3");

但是我想检查一个单独的数据库表:wp_usermeta,其中有一个字段meta_key='description',以查看其 是否为空或为空< / strong>用于关联的ID(来自第一个表匹配的user_id和ID)。

选择并打印wp_usermeta会产生:

Array
(
    [0] => stdClass Object
        (
            [umeta_id] => 19
            [user_id] => 2
            [meta_key] => first_name
            [meta_value] => Rita
        )

    [1] => stdClass Object
        (
            [umeta_id] => 20
            [user_id] => 2
            [meta_key] => last_name
            [meta_value] => Santos
        )

    [2] => stdClass Object
        (
            [umeta_id] => 21
            [user_id] => 2
            [meta_key] => nickname
            [meta_value] => rita
        )

    [3] => stdClass Object
        (
            [umeta_id] => 22
            [user_id] => 2
            [meta_key] => description
            [meta_value] => I’m the coolest person in Uniplaces. I also post stuff on Facebook and other social networks.
        )

我试过这个,我知道它给了我所有空洞的描述:SELECT * FROM wp_usermeta WHERE meta_key = 'description' AND meta_value = ''

但是我不确定如何组合它们以便在第一个查询中我只获得第二个表中的描述不为空或为空的结果。让我失望的另一件事是,我不确定如何将id带到第二个查询,因为第一个id具有不同的名称(ID而不是user_id)。

1 个答案:

答案 0 :(得分:1)

不是100%肯定我得到了你要求的东西,但是你可以使用附加数据和案例陈述来加入该表吗?

SELECT 
    ID
    , user_nicename 
    ,CASE 
        WHEN Len([meta_key='description'])>0 THEN 'Some Content'
        WHEN Len([meta_key='description'])=0 THEN 'No Content'
        WHEN [meta_key='description'] Is Null THEN 'Null'
        ELSE 'OTHER'
     END AS Category
from $wpdb->users as u
    left outer join wp_usermeta as m
        ON u.ID=m.user_id
WHERE display_name <> 'admin' 
ORDER BY rand() 
LIMIT 3

如果您只想查看不具有空或空描述的用户:

SELECT 
    ID
    , user_nicename 
    ,[meta_key='description']
from $wpdb->users as u
    INNER JOIN wp_usermeta as m
        ON u.ID=m.user_id
WHERE 
    display_name <> 'admin' 
    AND Len([meta_key='description'])>0
    AND [meta_key='description'] IS NOT NULL -- probably not required depending on len() behaviour
ORDER BY rand() 
LIMIT 3

或许你的第二个表中每个用户有多条记录,你想要meta_key = description?

SELECT 
    ID
    , user_nicename 
    ,meta_value
from $wpdb->users as u
    left outer join wp_usermeta as m
        ON u.ID=m.user_id
        AND meta_key='description'
WHERE 
    display_name <> 'admin' 
    AND Len(meta_value)>0
ORDER BY rand() 
LIMIT 3

我只是快速浏览一下表结构,我想你想要选项3