获取具有相同first_name的所有用户last_name

时间:2014-08-22 21:53:39

标签: mysql wordpress

我希望收到一个对象,其中包含Wordpress usermeta表中具有相同first_name的所有last_names用户。给出要搜索的first_name  即John Miller,John Doe和John Appleseed是我Wordpress页面上的注册用户。我想得到一个包括Miller,Doe和Appleseed的物品。

我尝试了以下查询,但它只返回由LIMIT 1

引起的last_name
SELECT `meta_value`
FROM `wp_usermeta`
WHERE `user_id` = (
    SELECT `user_id`
    FROM `wp_usermeta`
    WHERE `meta_value` LIKE 'John' AND
          `meta_key` = 'first_name'
    LIMIT 1
) AND `meta_key` = 'last_name';

如何修改此查询以接收所有用户last_names?

2 个答案:

答案 0 :(得分:1)

将表连接到自身以将名字与姓氏相关联,然后应用简单的相等WHERE子句:

SELECT
    f.user_id,
    f.meta_value AS first_name,
    l.meta_value AS last_name
FROM wp_usermeta f
INNER JOIN wp_usermeta l
    ON f.user_id = l.user_id AND
       f.meta_key = 'first_name' AND
       l.meta_key = 'last_name'
WHERE f.meta_value = 'John';

PostgreSQL中的示例执行(但查询也应该在MySQL中运行):

$ WITH wp_usermeta (user_id, meta_key, meta_value) AS (VALUES
    (1, 'first_name', 'John'),
    (1, 'last_name', 'Miller'),
    (2, 'first_name', 'John'),
    (2, 'last_name', 'Doe'),
    (3, 'first_name', 'John'),
    (3, 'last_name', 'Appleseed'),
    (4, 'first_name', 'Bob'),
    (4, 'last_name', 'Doe')
)
SELECT
    f.user_id,
    f.meta_value AS first_name,
    l.meta_value AS last_name
FROM wp_usermeta f
INNER JOIN wp_usermeta l
    ON f.user_id = l.user_id AND
       f.meta_key = 'first_name' AND
       l.meta_key = 'last_name'
WHERE f.meta_value = 'John';

 user_id | first_name | last_name
---------+------------+-----------
       1 | John       | Miller
       2 | John       | Doe
       3 | John       | Appleseed
(3 rows)

答案 1 :(得分:0)

只需将where user_id = (...更改为where user_id in (...,然后移除limit 1

即可
SELECT `meta_value`
FROM `wp_usermeta`
WHERE `user_id` in (
    SELECT `user_id`
    FROM `wp_usermeta`
    WHERE `meta_value` LIKE 'John' AND
          `meta_key` = 'first_name' 
) AND `meta_key` = 'last_name';