MySQL SQL - 如何在选择中隐藏列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43819781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 22:19:28  来源:igfitidea点击:

SQL - How to hide column in select

mysqlsql

提问by Black

I have two tables "contract" and "worker". I need to find the worker which has the most holidays left. However, I only need to print his name, not the holidays.

我有两个表“合同”和“工人”。我需要找到剩余假期最多的工人。但是,我只需要打印他的名字,而不是假期。

SCHEMA

架构



Contract:

合同:

Contract_ID (PK)
Worker_ID (FK)
holidays

Worker

工人

Worker_ID (PK)
Name

SAMPLE DATA:

样本数据:



contractContract

合同合同

workerWorker

工人工人

CODE

代码



Currently I print the information out with this code:

目前我用以下代码打印信息:

EDIT: The following SQL Code is wrong! It shows Fegeleineven though Klinkis the person with the most holidays.

编辑:以下 SQL 代码是错误的!它显示Fegelein即使Klink是假期最多的人。

SELECT W.Name, MAX(C.Holidays) As Holidays 
FROM worker AS W, contract AS C
WHERE W.Worker_ID = C.Worker_ID

Result:

结果:

Name    Holidays
Fegelein    31

Desired Result:

预期结果:

Name
Fegelein

SQL Fiddle: http://sqlfiddle.com/#!9/a840b/17

SQL小提琴http: //sqlfiddle.com/#!9/a840b/17

So I need to hide the second select MAX(C.Holidays) As Holidays. Is this possible?

所以我需要隐藏第二个 select MAX(C.Holidays) As Holidays。这可能吗?

回答by Gordon Linoff

Neveruse commas in the FROMclause. Alwaysuse proper, explicit JOINsyntax. Or, as a comment I saw yesterday suggests . . . JOINthe modern world.

切勿FROM子句中使用逗号。 始终使用正确、明确的JOIN语法。或者,正如我昨天看到的评论所暗示的那样。. . JOIN现代世界。

If you only want one such worker, then use LIMIT:

如果你只想要一个这样的工人,那么使用LIMIT

SELECT w.Name
FROM worker w JOIN
     contract c
     ON w.Worker_ID = c.Worker_ID
ORDER BY c.Holidays DESC
LIMIT 1;

Mostholidays appears to be the smallest value of holiday. If it is the smallest value (as suggested by your question), use ORDER BY c.Holidays ASC.

大多数假期似乎是 的最小值holiday。如果它是最小值(如您的问题所建议的那样),请使用ORDER BY c.Holidays ASC.

Presumably, workers might be on multiple contracts, so you might want aggregation. However, that is unclear.

据推测,工人可能有多个合同,因此您可能需要聚合。然而,这还不清楚。

Hereis a SQL Fiddle.

是一个 SQL 小提琴。

回答by Sanchit Gupta

Simply try with :

只需尝试:

SELECT w.Name
FROM worker w JOIN
     contract c
     ON w.Worker_ID = c.Worker_ID
ORDER BY c.Holidays DESC

You can add LIMIT 1if you need only one result.

LIMIT 1如果您只需要一个结果,您可以添加。

回答by Web Artisan

I think this should do your job.

我认为这应该可以完成您的工作。

SELECT W.Name
FROM worker AS W, contract AS C
where W.Worker_ID = C.Worker_ID order by C.Holidays limit 1;

Delete Holidays from select attributes and limit it to 1 and orderby Holidays does the job

从选择属性中删除 Holidays 并将其限制为 1 并且 orderby Holidays 完成这项工作