开发者

Join two tables, then Order By date, BUT combining both tables

Alright, I'm trying to figure out why I can't understand how to do this well...

I have two tables:

So, the goal here is to join both tables, where the userID matches whatever I want it to be - and then return everything ordered by date (most recent at the top). However, because there is a date field in each of the tables, I'm not sure how MySQL will handle things... will is sort by both dates automatically? Here's what I was thinking...

"SELECT DISTINCT *
            FROM invoices,payments
            WHERE {$userID} = invoice.userID
            OR {$userID} = payments.userID
            ORDER BY date DESC";

But, it's starting to become clear to me that maybe this isn't even the right use of a join command... maybe I need to just get all data on each table alone, then try to sort it somehow with PHP? If that's the better method, what's a good way to do this type of DATE sort while keeping all row data in tact?

I should add, the TIME inside the unix timestamp (that's how "date" is stored) is NOT negligible - it should sort by the date and time.

Thanks all...


If the columns of both tables are the same, you can use a UNION

SELECT X.*
  FROM ( SELECT `id`,
                `userID`,
                 'INVOICE' AS PTYPE
                 `amount`,
                 `date`
            FROM `invoices`
           WHERE {$userID} = userID  
          UNION
          SELECT `id`,
                 `userID`,
                 'PAYMENT' AS PTYPE
                 `amount`,
                 `date`
            FROM `payments`
           WHERE {$userID} = userID  
        ) X
 ORDER BY X.`date`

EDIT

Read the relevant section of the MySQL manual on UNIONS. There are other ways of phrasing this, but this is my preferred style - it should be clear to anybody reading that the ORDER BY clause applies to the result of both sides of the UNION. A carelessly written UNION - even with an ORDER BY - may still leave the final resultset in indeterminate order.

The purpose of the PTYPE is that this query returns an extra column called PTYPE, that indicates whether each individual row is an INVOICE or a PAYMENT... ie. which of the two tables it comes from. It's not mandatory, but can often be useful within a union


Because you have two identical fields named date, MySQL will not know which one you're trying to order by.

"SELECT DISTINCT *
            FROM invoices,payments
            WHERE {$userID} = invoice.userID
            OR {$userID} = payments.userID
            ORDER BY invoices.date, payments.date DESC";

This would sort on the invoice date, then the payment date - if that's what you are trying to find out


If your data tipe is Date, Timestamp, or anything related, the SGBD will order it properly. If that was what you've asked.

But if the datatype is String, even when dates is store, it will not sort the way you want.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜