尝试合并两个表时出现MySql错误

时间:2019-01-11 00:36:59

标签: mysql sql database sql-like android-room

嗨,我在尝试合并两个表Post和User时遇到以下错误

  

错误:期望{,';',K_ALTER,K_ANALYZE,>> K_ATTACH,K_BEGIN,K_COMMIT,K_CREATE,K_DELETE,K_DETACH,   K_DROP,K_END,K_EXPLAIN,K_INSERT,K_PRAGMA,K_REINDEX,K_RELEASE,   K_REPLACE,K_ROLLBACK,K_SAVEPOINT,K_SELECT,K_UPDATE,K_VACUUM,   K_VALUES,K_WITH,UNEXPECTED_CHAR}

我有一个表,表中包含许多帖子,其中包括标题,正文以及用户创建该帖子的方式,

用户表是用户详细信息的列表,例如名称和地址。

我试图创建一个结果集,以输出帖子的详细信息,例如标题和正文,以及附加的用户名(帖子表仅具有用户ID引用)

这是我尝试过的查询

SELECT post.title AS title, post.body AS body, post.username AS username FROM post, user, WHERE user.id = post.userId

我的sql技巧有点生锈,但是我相信可以完成上述用例查询?

3 个答案:

答案 0 :(得分:1)

听起来您想要表联接。我假设您在写post.username时是指user.username,因为您稍后会说post表仅具有一个userId引用。

您可能想要这样的东西

SELECT post.title, post.body, user.username
FROM post
INNER JOIN user
ON post.userId=user.id;

答案 1 :(得分:0)

您应该尝试这样的事情:

SELECT p.title AS title,p.body AS body,p.username AS username 
FROM post p 
JOIN user u ON u.id = p.userId
WHERE u.id = 'to your user id'

答案 2 :(得分:0)

您的查询看起来不错,但是删除where子句之前的逗号:

来自

SELECT post.title AS title, post.body AS body, post.username AS username FROM post, user, WHERE user.id = post.userId

SELECT post.title AS title, post.body AS body, post.username AS username FROM post, user WHERE user.id = post.userId