Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - How to hide column in select

Tags:

sql

mysql

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:


contract Contract

worker Worker

CODE


Currently I print the information out with this code:

EDIT: The following SQL Code is wrong! It shows Fegelein even though Klink is the person with the most holidays.

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

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

like image 490
Black Avatar asked Jun 14 '26 22:06

Black


2 Answers

Never use commas in the FROM clause. Always use proper, explicit JOIN syntax. Or, as a comment I saw yesterday suggests . . . JOIN the modern world.

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

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

Most holidays 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.

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

Here is a SQL Fiddle.

like image 119
Gordon Linoff Avatar answered Jun 17 '26 22:06

Gordon Linoff


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 1 if you need only one result.

like image 21
Sanchit Gupta Avatar answered Jun 17 '26 23:06

Sanchit Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!