mysql join query order by two columns

2020-04-18 07:00发布

问题:

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.