我在这个问题上坚持了整整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 |
+--------+--------+-------------+----------------------------+--------------------------------------------+
明天我要开会,展示我的原型应用程序。将不胜感激。
答案 0 :(得分:2)
您正在使用子查询而非联接。在select中使用子查询时,必须确保它像
一样返回一行SELECT COL1,COL2,(SELECT 1) from YourTable
或者通过使用相关查询,我认为这是您的目的但不是必需的,因为它来自您选择的同一个表,所以只需使用一个简单的连接:
SELECT s.*, t.profile_pic
FROM users t
INNER JOIN userpost s on t.userId = s.userId
答案 1 :(得分:0)
试试这个......
SELECT *,
(SELECT top 1 profile_pic FROM users a
where a.userId = b.userId order by b.postId desc) as profile_pic
FROM userpost b
但我不确定,上面的查询会返回所需的个人资料图片。
答案 2 :(得分:-1)
您没有正确使用子查询。您应该确保子查询只返回一行。
以下是您需要的查询。
Select up.postId,u.userId,up.postMessage,up.postImage,u.profile_pic from user u
inner join userpost up on u.userId=up.userId