Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SELECT DISTINCT and CONCAT in the same SQL statement

So I am feeding the results of this SQL into an array. The array later becomes the suggestions for a textbox that operates while typing. I want it to only return each name 1 time, even if the person has multiple appointments. Currently, this returns all appointments for the person with that name, so if "Brad Robins" has 5 appointments, and I start to type "Brad", it displays "Brad Robins" 5 times in the suggestions instead of only once.

$sql = "SELECT DISTINCT CONCAT(clients.studentFirstName, ' ', clients.studentLastName) AS name, appointments.location, appointments.subLocation, appointments.appointmentAddress1, appointments.appointmentAddress2, appointments.appointmentCity, appointments.appointmentState, appointments.appointmentZip, appointments.startTime, appointments.endTime, appointments.date, clients.school
                    FROM appointments JOIN clients
                    ON appointments.clientID = clients.clientID
                    WHERE CONCAT(clients.studentFirstName, ' ', clients.studentLastName) = '".$roommate."' AND clients.school = '".$school."';";

To me, it just seems like DISTINCT and CONCAT aren't playing nicely together.

like image 776
radleybobins Avatar asked Jan 27 '12 01:01

radleybobins


2 Answers

Distinct goes against the entire row of ALL columns, not just the name portion... So if the appointments are on different date/times, locations, etc, they will all come out. If all you want to show is the NAME portion, strip the rest of the other content. Query the available appointments AFTER a person has been chosen.

like image 118
DRapp Avatar answered Sep 24 '22 08:09

DRapp


Don't use DISTINCT, use group by:

$sql = "SELECT CONCAT(clients.studentFirstName, ' ', clients.studentLastName) AS name, appointments.location, appointments.subLocation, appointments.appointmentAddress1, appointments.appointmentAddress2, appointments.appointmentCity, appointments.appointmentState, appointments.appointmentZip, appointments.startTime, appointments.endTime, appointments.date, clients.school
                FROM appointments JOIN clients
                ON appointments.clientID = clients.clientID
                WHERE CONCAT(clients.studentFirstName, ' ', clients.studentLastName) = '".$roommate."' AND clients.school = '".$school."' group by CONCAT(clients.studentFirstName, ' ', clients.studentLastName);";

Also be careful about XSS in $school and $roomate if this accessible outside.

like image 38
vimdude Avatar answered Sep 23 '22 08:09

vimdude