我有两个表格如下所示
表1
ID username
1 johndoe
2 mikeb
表2
ID user_id meta_key meta_value
23 1 my_pin 12345
24 2 my_pin 67890
我正在尝试编写一个将返回
的mySQL查询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
此操作失败,因为子查询返回多行。有人能指出我正确的方向吗?
修改:其他信息
为了简化我的问题,我遗漏了一些细节(抱歉)。 表2有多个条目
表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
我需要查询返回
ID username my_pin my_id
1 johndoe 12345 10011
2 mikeb 67890 10012
那么,如果我使用“简单”连接,WHERE子句应该是什么样的?
答案 0 :(得分:0)
加入这两个表将为您提供所需的所有信息,您可以使用WHERE
子句仅选择所需的结果。
SELECT ID, meta_value as my_pin
FROM table1
INNER JOIN table2
ON table1.ID = table2.user_id
WHERE table2.meta_key = "my_pin"
答案 1 :(得分:0)
这是通过简单的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
答案 2 :(得分:0)
感谢那些回复的人。以下是我提出的解决更新问题的方法。
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"