简体   繁体   English

从一个表中选择记录,并使用另一表中的列对结果进行排序

[英]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. 我正在为位于我公司的CRM的薪资系统工作,我正试图省去存储冗余数据的麻烦,这些冗余数据将在几年内堆积起来。

I tried to relate it to " how to get value from mysql table ordered by another table? " but had no luck. 我试图将其与“ 如何从另一个表排序的mysql表中获取价值? ”联系起来,但是没有运气。

I have a Users table 我有一个Users

===========================================
# 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. 我还有一个Timesheets表,用于存储每个会话的数据,为了简短起见,我在这个问题上做了一些总结,显然错过了开始和结束的完整日期/时间。

============================================
# 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. 我要实现的是通过Users表中的last_name列对Timesheets表中的结果进行排序,仅使用派生自Timesheets表的用户名。

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? MySQL显然不是我的利基市场,哪种查询可以提供所需的结果?

You'd have to use a JOIN and then ORDER BY , like this: 您必须先使用JOIN然后使用ORDER BY ,如下所示:

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 . 您可以根据需要在ORDER BY之前添加WHERE子句。

Use JOIN : 使用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: 为此使用join:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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