简体   繁体   中英

Select records from one table and sort the result using a column from another table

I'm working on payroll system for the CRM located at my work and I'm trying to save having to store redundant data which over a period of years will stack up.

I tried to relate it to " how to get value from mysql table ordered by another table? " but had no luck.

I have a Users table

===========================================
# id | username | first_name | last_name  #
===========================================
# 1  |   joe    |    Joe     |    Blow    #
===========================================

I also have a Timesheets table which stores the data of each individual session which for the sake of keeping short I have condensed a little in this question and obviously misses the full date/time in start and finish.

============================================
# id | username |    start   |   finish    #
============================================
# 1  |   joe    |   00:00    |    23:59    #
============================================

What I want to achieve is to order the results from the Timesheets table by the last_name column in the Users table with just the username that is derived the Timesheets table.

What I am trying to attempt here:

SELECT * FROM `Timesheets` WHERE `start` >= '{$monday}' AND `finish` <= '{$sunday}' ORDER BY (`Users`.`last_name` WHERE `username` = `Timesheets`.`username`)  ASC

MySQL is clearly not my niche, what query would provide the desired result?

You'd have to use a JOIN and then ORDER BY , like this:

SELECT ts.*
FROM timesheets ts
JOIN users
ON ts.username = users.username
ORDER BY users.last_name

You may add the WHERE clause as required before the ORDER BY .

Use JOIN :

SELECT *
FROM Timesheets T
JOIN Users U ON T.username = U.username
WHERE T.start >= '{$monday}' AND `finish` <= '{$sunday}'
ORDER BY U.last_name ASC

use join for this:

SELECT t.*
FROM timesheets t
JOIN users
ON t.username = users.username  WHERE t.start >= '{$monday}' AND t.finish <= '{$sunday}'
ORDER BY users.last_name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM