问题
So basically I'm getting notifications of new content on my website. I have 4 tables -
- articles
- media
- updates
- comments
Each table has a set of its own columns (I can include these if anyone wants). There is one distinct column every table has, this is the timestamp column (a big int formatted column with data from the PHP time() function). My solution to getting the last 30 modifications is to select the first 30 rows from these 4 tables ordered by timestamp descending.
Here is the query I have so far, it doesn't work and I'm wondering if someone could help me. -
SELECT * FROM `articles`
UNION SELECT * FROM `media`
UNION SELECT * FROM `updates`
UNION SELECT * FROM `comments`
ORDER BY `timestamp` DESC
LIMIT 30
EDIT: I was also using another query before -
SELECT * FROM `articles` ,`media` ,`updates` ,`comments`
ORDER BY `timestamp` DESC
LIMIT 30
and kept getting this error - Column 'timestamp' in order clause is ambiguous
EDIT 2
I realise now I have to use the AS clause in my statement to combine these results into one table.
回答1:
SELECT a.*,m.*,u.*,c.* from articles AS a
LEFT JOIN media AS m ON (m.timestamp = a.timestamp)
LEFT JOIN updates AS u ON (u.timestamp = a.timestamp)
LEFT JOIN comments AS c ON (c.timestamp = a.timestamp)
ORDER BY timestamp desc LIMIT 30
回答2:
Your union can work, but only if you can create some sort of common field list. For example, lets say you have a description field in each table, with different names. Something like this will work...
SELECT TimeStamp,'Articles',Art_desc AS Description FROM articles
UNION ALL
SELECT TimeStamp,'Media',Media_Desc FROM Media
UNION ALL
SELECT TimeStamp,'Updates',Update_Desc FROM Updates
UNION ALL
SELECT TimeStamp,'Comments',Comment FROM Comments
ORDER BY timeStamp DESC LIMIT 30
In essence, you are creating result sets of 3 consistent columns, so UNION will work in this case.
来源:https://stackoverflow.com/questions/7494392/how-to-structure-this-sql-query