【问题标题】:How to output a mixture of data from 2 mySQL tables when joined columns have similar names?当连接列具有相似名称时,如何从 2 个 mySQL 表中输出混合数据?
【发布时间】:2015-04-06 22:20:42
【问题描述】:

我想要实现的是在一个按时间戳排序的循环中显示特定user_id 的所有已发表文章和所有已发表问题。简而言之,将文章和问题混合在一起显示所有内容。

我的数据库结构如下,我也放了profiles表。

我的错误sql查询是:

SELECT * 
FROM articles
JOIN questions ON articles.user_id = questions.user_id
WHERE articles.user_id =  '38'
AND questions.user_id =  '38'
AND questions.publish =  '1'
AND articles.publish =  '1'
ORDER BY questions.timestamp DESC

文章表

id
publish
user_id
user_name
article_title
article_content
article_category
timestamp

问题表

id
publish
user_id
user_name
question_title
question_content
question_category
timestamp

个人资料

user_id

【问题讨论】:

  • 使用UNION,而不是JOIN
  • 这个问题已经回答过很多次了。寻找“别名”

标签: mysql sql tsql


【解决方案1】:

只需使用连接,外连接会从两个表中获取所有匹配记录:

SELECT * 
FROM articles
FULL OUTER JOIN questions ON articles.user_id = questions.user_id
WHERE articles.user_id =  '38'
ORDER BY questions.timestamp DESC

【讨论】:

    猜你喜欢
    • 2018-10-16
    • 2017-06-18
    • 1970-01-01
    • 2012-05-30
    • 2018-11-20
    • 2020-07-16
    • 2014-07-13
    • 1970-01-01
    • 2013-04-19
    相关资源
    最近更新 更多