[英]mysql query select from multiple, order by date
What's a good and simple way to select from multiple tables and just order everything by date, newest to oldest? 从多个表中进行选择并按日期顺序(从最新到最旧)进行排序的一种好简单方法是什么?
mysql_query("
SELECT *
FROM posts, comments, photos
WHERE userID='$session'
ORDER BY date");
if I wanted to do something like that. 如果我想做这样的事情。
SELECT *
FROM (SELECT userID, Col1, Col2, Col3, date
FROM posts
UNION
SELECT userID, Col1, Col2, Col3, date
FROM comments
SELECT userID, Col1, Col2, Col3, date
FROM photos ) t
WHERE userID = 123
ORDER BY date DESC
Your existing query won't do what you want. 您现有的查询将无法满足您的需求。 Instead you need to
JOIN
your tables on some common column: 相反,您需要将表
JOIN
到一些公共列上:
SELECT
posts.*,
comments.*,
photos.*
FROM
posts JOIN comments ON posts.post_id = comments.post_id
JOIN photos ON posts.post_id = photos.post_id
ORDER BY posts.date DESC
Note that it is often not advisable to do SELECT *
or SELECT posts.*
in production code. 请注意,通常不建议在生产代码中执行
SELECT *
或SELECT posts.*
。 It is typically better to explicitly list the columns you want so you can be sure of the order they arrive in (which matters for UNION
queries, for example), and if your schema changes. 通常最好显式列出所需的列,这样可以确保它们到达的顺序(例如,这对于
UNION
查询很重要)以及架构是否更改。
SELECT
posts.date,
posts.post_id,
posts.title,
posts.etc,
comments.date,
comments.user,
comments.text,
photos.title
FROM
posts JOIN comments ON posts.post_id = comments.post_id
JOIN photos ON posts.post_id = photos.post_id
/* Also, if multiple tables have a `date` column, you'll need to specify which one
as in `posts`.`date` */
ORDER BY posts.date DESC
To use an ORDER BY or LIMIT clause to sort or limit the entire UNION result, parenthesize the individual SELECT statements and place the ORDER BY or LIMIT after the last one.
要使用ORDER BY或LIMIT子句对整个UNION结果进行排序或限制,请在各个SELECT语句之间加上括号,然后将ORDER BY或LIMIT放在最后一个语句之后。 The following example uses both clauses:
下面的示例使用两个子句:
(SELECT a FROM t1 WHERE a=10 AND B=1) UNION
(SELECT a FROM t2 WHERE a=11 AND B=2)
ORDER BY a LIMIT 10;
A statement without parentheses is equivalent to one parenthesized as just shown.
如前所述,不带括号的语句等效于一个带括号的语句。
This kind of ORDER BY cannot use column references that include a table name (that is, names in tbl_name.col_name format).
这种ORDER BY无法使用包含表名(即tbl_name.col_name格式的名称)的列引用。 Instead, provide a column alias in the first SELECT statement and refer to the alias in the ORDER BY.
而是在第一个SELECT语句中提供列别名,并在ORDER BY中引用该别名。 (Alternatively, refer to the column in the ORDER BY using its column position. However, use of column positions is deprecated.)
(或者,使用其列位置引用ORDER BY中的列。但是,不建议使用列位置。)
-> http://dev.mysql.com/doc/refman/5.0/en/union.html -> http://dev.mysql.com/doc/refman/5.0/en/union.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.