我在整个问题上呆了整整2天。我有一个users
表,它包含:
+--------+--------+----------+--------------------------------------------+
| userId | name | username | profile_pic |
+--------+--------+----------+--------------------------------------------+
| 1 | john | john123 | http://localhost/profile_pic/user1pic.jpg |
| 2 | andrew | andrew | http://localhost/profile_pi/user2pic.jpg |
| 3 | doe | doe | http://localhost/profile_pic/user3pic.jpg |
+--------+--------+----------+--------------------------------------------+
我有另一个名为
userpost
的表,其中包含:+--------+--------+-------------+----------------------------+
| postId | userId | postMessage | postImage |
+--------+--------+-------------+----------------------------+
| 1 | 1 | "Hey" | http://localhost/post1.jpg |
| 2 | 3 | "Add me" | http://localhost/post2.jpg |
| 3 | 2 | "boring" | http://localhost/post3.jpg |
+--------+--------+-------------+----------------------------+
userId
引用为users.userId
。我正在尝试将profile_pic
加入userpost
,但是mysql返回错误。这是我在做什么: SELECT *, (SELECT profile_pic FROM users
INNER JOIN userpost on users.userId = userpost.userId) as profile_pic FROM userpost
但是出现
Subquery returns more than 1 row
错误我知道我在查询中做一些愚蠢的事情。我只想要这样的东西:
+--------+--------+-------------+----------------------------+--------------------------------------------+
| postId | userId | postMessage | postImage | profile_pic |
+--------+--------+-------------+----------------------------+--------------------------------------------+
| 1 | 1 | "Hey" | http://localhost/post1.jpg | http://localhost/profile_pic/user1pic.jpg |
| 2 | 3 | "Add me" | http://localhost/post2.jpg | http://localhost/profile_pic/user3pic.jpg |
| 3 | 2 | "boring" | http://localhost/post3.jpg | http://localhost/profile_pi/user2pic.jpg |
+--------+--------+-------------+----------------------------+--------------------------------------------+
我明天开会,展示我的原型应用程序。帮助将不胜感激。
最佳答案
您正在使用子查询而不是联接。在选择中使用子查询时,必须确保它返回的确是一行,例如
SELECT COL1,COL2,(SELECT 1) from YourTable
或通过使用相关查询,我认为这是您的目的,但不是必需的,因为它来自与您选择的表相同的表,因此只需使用简单的联接即可:
SELECT s.*, t.profile_pic
FROM users t
INNER JOIN userpost s on t.userId = s.userId