mysql join query order by two columns

限于喜欢 提交于 2019-12-02 06:02:24

问题


I am trying to join two tables and in both tables I have 2 same column names like agent_id and date both tables have agent_id and date actually I join tables based on agent_id and now I want to order by date column but as both tables have date column so it's showing that date column twice I want it should be shown once and order by date here is an example of my tables:

Table 1 (sales_report)
date          agent_id  agent_name  agent_commission
01-Jan-2016   1         Jhon         200   
02-Jan-2016   2         Smith        250 
03-Jan-2016   3         Tracy        150
04-Jan-2016   4         Sam          120

Table 2 (payments)
date          agent_id  paid
02-Jan-2016   1         200   
03-Jan-2016   2         150 
04-Jan-2016   3         100
05-Jan-2016   4         50

I tried to join these both tables by agent_id now my question is how can I order by date ?

Here is the query I have:

SELECT *
FROM `sales_report`
INNER JOIN `payments`
ON `sales_report`.`agnt_id`=`payments`.`agnt_id` ORDER BY date

回答1:


    SELECT sr.*,pm.paid
    FROM `sales_report` as sr
    INNER JOIN `payments` as pm
    ON sr.`agent_id`=pm.`agent_id` 
    ORDER BY sr.date, pm.date

Will get you date from first table and order by 1st table date then 2nd table date.




回答2:


    SELECT * FROM
    (
         SELECT sr.date
            FROM `sales_report` as sr
         UNION
         SELECT pm.date
            FROM `payments` as pm
        )
    ORDER BY date

I think this is what you wanted,Both sales_report and payments need be considered as a table.then sort it.



来源:https://stackoverflow.com/questions/39038412/mysql-join-query-order-by-two-columns

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