复杂 mySQL 两个 Table 查询

Complex mySQL Two Table Query

我有两个表格如下所示

Table 1

ID  username  
1   johndoe  
2   mikeb

Table 2

ID  user_id     meta_key    meta_value  
23      1       my_pin      12345  
24      2       my_pin      67890 

我正在尝试编写一个 mySQL 查询,它将 return

ID   username    my_pin  
 1   johndoe     12345  
 2   mikeb       67890 

我的方法是使用子查询,但它不起作用。

SELECT 
    ID, 
    (SELECT meta_value 
     FROM table1 
     WHERE meta_key = "my_pin"
       AND table1.ID = table2.user_id) as my_pin 
FROM 
    table1
INNER JOIN 
    table2 ON table1.ID = table2.user_id

这失败了,因为子查询 return 有多行。谁能指出我正确的方向?

编辑:附加信息

为了简化我的问题,我遗漏了一些细节(抱歉)。 Table 2 有多个条目

Table 2

ID  user_id     meta_key    meta_value  
23      1       my_pin      12345  
24      2       my_pin      67890 
25      1       my_id       10011
26      2       my_id       10012

我需要查询 return

ID   username    my_pin  my_id
 1   johndoe     12345   10011
 2   mikeb       67890   10012

那么,如果我使用 "simple" 连接,WHERE 子句应该是什么样的?

连接两个表将为您提供所需的所有信息,您可以使用 WHERE 子句来 select 仅提供您需要的结果。

SELECT ID, meta_value as my_pin
FROM table1
INNER JOIN table2
  ON table1.ID = table2.user_id
WHERE table2.meta_key = "my_pin"

这是用一个简单的 JOIN:

SELECT t1.username, t2.meta_value AS my_pin
FROM table1 AS t1
JOIN table2 AS t2 ON t1.ID = t2.user_id
WHERE t2.meta_key = "my_pin"

您也可以通过加入子查询来实现:

SELECT t1.username, t2.meta_value AS my_pin
FROM table1 AS t1
JOIN (SELECT user_id, meta_value
      FROM table2
      WHERE meta_key = "my_pin") AS t2
ON t1.ID = t2.user_id

感谢回复的人。这是我想出的解决更新问题的办法。

    SELECT t1.ID, t1.username,
    (
    SELECT meta_value
          FROM t2.wp_usermeta
          WHERE meta_key = "my_id"
          AND user_id = t1.ID
    ) as my_id,
    (
    SELECT meta_value
          FROM t2.wp_usermeta
          WHERE meta_key = "my_pin"
          AND user_id = t1.ID
    ) as my_pin
    FROM table1 AS t1
    INNER JOIN table2 AS t2
    ON t1.ID = t2.user_id
    WHERE t2.meta_key = "my_pin"