简体   繁体   中英

How to output a mixture of data from 2 mySQL tables when joined columns have similar names?

What I want to achieve is to show all the published articles and all the published questions of a specific user_id in one loop ordered by timestamp. In simple words, to show everything mixing articles and questions.

My database structure is as below, and I have put also the profiles table.

My wrong sql query is :

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

Articles table

id
publish
user_id
user_name
article_title
article_content
article_category
timestamp

Questions table

id
publish
user_id
user_name
question_title
question_content
question_category
timestamp

Profiles

user_id

Just use a join, an outer join will get all matching records from both table:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM