Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to distinct on a single column in a query in SQL?
    primarykey
    data
    text
    <p>I have a webapp for a school that pulls the locations of both students and faculty when they register for the system. These locations change over time, though (students change dorm, staff switch buildings), so I'm building a script to update them occasionally. I need to run a query that pulls in a list of userids and building names, and I'd like to do it in a single query for personal edification/masochistic reasons.</p> <p>I have access to a central database that has the following (simplified) schema:</p> <pre><code>facstaff(userid, bldgcode) students(userid, dorm) buildings(bldgcode, building) # building is the human readable building name </code></pre> <p>and the query that I'm working with so far looks like this:</p> <pre><code>SELECT users.userid, buildings.building FROM (SELECT userid, bldgcode FROM facstaff UNION SELECT userid, dorm AS bldgcode FROM students) AS users INNER JOIN buildings ON users.bldgcode=buildings.bldgcode WHERE userid in (&lt;list of users&gt;); </code></pre> <p>&nbsp;</p> <p>The issue I'm having is that many students go on to work in the school after they graduate (student entries are not removed from the db on graduation), or will work and study simultaneously, so there are duplicate <code>userid</code> after my union, but they have different <code>bldgcode</code> so a simple distinct doesn't work. Basically I get results like this:</p> <pre><code>+----------+-----------------------+ | userid | building | +----------+-----------------------+ | jimbo | Science Sphere | | billiam | Dorm E11 | | dwayne | Humanities Hall | | mandar | Science Sphere | | foobaz | Administration | | fredrick | Physical Plant | | fredrick | Dorm A6 | +----------+-----------------------+ </code></pre> <p>Fredrick is both a student and a staff member, so two locations come up with his name; one from <code>facstaff</code> and one from <code>students</code>. Ideally, there would be a way to enforce distinction in the <code>userid</code> column so that the building coming from <code>facstaff</code> would override anything coming out of <code>students</code>. I'm open to other solutions though, of course. I appreciate any help!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload