Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

SQL - Query relating to date range from one table and two other tables

I am new to SQL, starting today at college.

I need to find the telephone number of owners who took their pet for a visit in May 2020.

I have the following tables with the columns and some example data:

Visit:
Pet_ID, Vet_Id, Date, Time, Reason, Treatment
P0089 - V04 - 03/05/2020 - 17:50 - Limping - Ointment
P0001 - V04 - 07/05/2020 - 21:00 - Cut on nose and leg - Ointment

Pet:
Pet_ID, Name, Type, Breed, Gender, Born, Owner_ID, Notes
P0001 - Tiddles - Cat - Persian - F - 2009 - 2 - Has a bad temper & Scratches
P0089 - Ginger - Cat - Siamese - F - 2016 - 4 - Bad tempered

Owner:
Owner_ID, Surname, Forename, Title, Tel_Number, Address
1 - Jackson - Janet - Miss - 0141-223321 - 1 Main Street, Glasgow
2 - Singh - Raj - Mr - 0141-326535 - 22, The Hill, Glasgow

I have tried the following command.

SELECT Owner.Tel_Number
FROM Owner, Pet, Visit
WHERE Visit. Date_ BETWEEN "01/05/2020" AND "31/05/2020" 
AND Visit.Pet_id = Pet.Pet_id
AND Pet.Owner_id = Owner.Owner_id
GROUP BY Owner.Tel_Number

But the result shows the telephone number for all owners? What am I doing wrong? Thank you.

EDIT: Apologies, I am using DB Browser for SQLite, not Oracle or anything other system like that. This is for college. And I have added some example data.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Always use proper, explicit, standard*, readable JOIN syntax.

However, your problem is probably the format of the date strings. This should always be in standard format. I would suggest:

SELECT o.Tel_Number
FROM Owner o JOIN
     Pet p
     ON p.Owner_id = o.Owner_id JOIN
     Visit v
     ON v.Pet_id = p.Pet_id
WHERE v.Date_ >= '2020-05-01' AND
      v.Date_ < '2020-06-01'
GROUP BY o.Tel_Number

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...