开发者

how to order a mysql selection

I'm selecting data from two different tables which have a common field "date" and i want to order by date desc but i can't get it to work and i haven't found much help googleing about it.

SELECT table1.id, tabl开发者_C百科e1.date, table2.id, table2.date FROM table1, table2 ORDER BY  

Also i would appreciate any links to read more about these types of queries, it would save me from having to ask here for help all the time :D Thanks.


Unless you want a full-blown cartesian product (where you combine every row in table 1 with every row in table 2), you'll need a limiting where clause, something like:

select    a.id, b.id, b.date
from      table1 a, table2 b
where     a.date = b.date
order by  b.date desc

The where clause in the above select will only combine rows from the two tables where the dates are identical, which is what it sounds like you need.

If instead, you want to get the ID and date from two different tables and sort by the date, you probably need something like:

select      id, date
from        table1
union all
select      id, date
from        table2
order by    2 desc

This will return the IDs and dates from both tables, unioned together, then sort using a column number rather than name.


Something like:

SELECT table1.id, table1.date, table2.id, table2.date FROM table1, table2 ORDER BY table1.date

An introduction to SQL ORDER BY could be found here: http://www.w3schools.com/sql/sql_orderby.asp.


SELECT table1.id, table1.date, table2.id, table2.date FROM table1, table2 ORDER BY  table2.date DESC

if you want to order by table2's date

OR

SELECT table1.id, table1.date, table2.id, table2.date FROM table1, table2 ORDER BY  table1.date DESC


You could use UNION ALL to combine the table queries, something like this:

SELECT * FROM
(
    SELECT 1 AS id, date FROM table1
    UNION ALL
    SELECT 2 AS id, date FROM table2
) T1
ORDER BY date
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜