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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-06 13:56:55

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!