43

I have a database with two tables. One of the tables contains users, the other contains addresses for those users. Each user may have several addresses (though each address is tied to only one user.)

I want to create a search that only returns one entry for each user, even if that user has several addresses. It doesn't matter which address the search pulls back - whatever the search finds first is enough.

Here is an example search result:

tst  olix  Chicago  IL  USA
tst  olix  Los Angeles  CA  USA
tst2 olix2 Houston  TX USA

I need the search to be such that it only returns 2 rows, rather than 3.

Any ideas?

SELECT DISTINCT
    Users.Firstname, Users.Surname, Users.UserId, 
    Users.Recommendations, Addresses.City, Addresses.Region,
    Addresses.Country
FROM
    Users INNER JOIN
    Addresses ON FT_TBL.UserId = Addresses.UserId
ORDER BY
    Users.Recommendations
2
  • What do you use, SQL-Server or Access ? Jul 22, 2011 at 16:39
  • 1
    If this was postgresql you could just use DISTINCT ON syntax.
    – sage88
    Feb 17, 2017 at 1:06

5 Answers 5

17

You probably need to use GROUP BY instead of DISTINCT in this case.

Post your query now and I will help you more.

Alternatively, if you just want to return the first address, that's a different query entirely. Does it need to return the address? What data do you need? What does "first" mean in this context? How is the data ordered?

Arbitrarily you could do something like this (untested), depending on your DB:

SELECT 
    userID
    , FIRST(address)
FROM
    yourTable
GROUP BY
    userID
1
  • Eventually I want it to be a location search, and the result pulled back is the closest place to a certain location. At the moment I just want it to pull back something while I work on the design of the site.
    – Oliver
    Jul 22, 2011 at 15:46
13

If Addresses has an ID field:

(updated for SQL-Server)

SELECT 
    Users.Firstname,
    Users.Surname,
    Users.UserId, 
    Users.Recommendations,
    Addresses.City,
    Addresses.Region,
    Addresses.Country
FROM
    Users INNER JOIN
    Addresses ON Users.UserId = Addresses.UserId
WHERE Addresses.ID = 
    ( SELECT TOP 1 A2.ID
      FROM Addresses AS A2
      WHERE Users.UserId = A2.UserId
    )
ORDER BY
    Users.Recommendations

Using SQL-Server's window and ranking functions:

SELECT 
    Users.Firstname,
    Users.Surname,
    Users.UserId, 
    Users.Recommendations,
    Addresses.City,
    Addresses.Region,
    Addresses.Country
FROM
    Users INNER JOIN
     ( SELECT *
            , ROW_NUMBER() OVER (PARTITION BY UserID) AS rn
       FROM Addresses
     ) AS Addresses ON Users.UserId = Addresses.UserId
                    AND Addresses.rn = 1
ORDER BY
    Users.Recommendations
3
  • That looks a more handy than the < comparison I ended up using. But alas, microsoft sql doesn't have LIMIT.
    – Oliver
    Jul 22, 2011 at 16:27
  • @Oliver: And also window functions which should be handy in this case. Jul 22, 2011 at 16:30
  • I like the top solution, but think that using a windowing function for this is like killing a gnat with a sledgehammer :) I guess it is interesting to show it can be done that way though.
    – dana
    Jul 23, 2011 at 1:45
9
SELECT Name, MAX(Address), MAX(other field)...
FROM MyTable
GROUP BY Name

Will give you one row per Name.

3
  • 1
    +1 your answer, like mine depends on some arbitrary order. OP should clarify.
    – Matthew
    Jul 22, 2011 at 15:37
  • 4
    @Matthew - he says in the question he doesn't care which one he gets. I think he might care if the fields are interrelated (i.e. Address1, City, State, Zip) - you could get the wrong state/address combination which would be bad
    – JNK
    Jul 22, 2011 at 15:38
  • Exactly, like: Los Angeles | IL | USA. Jul 22, 2011 at 15:55
6

Assuming the address table has an id column:

select p.fname, p.lname, a.state, a.country
from person p
join address a on a.personid = p.personid
where not exists
    (select *
    from address a2
    where a2.personid = a.personid
      and a2.addressid < a.addressid)

My query returns all people with addresses. The exists() clause is used to determine that the returned address has the lowest addressid assigned to the person. The result will only contain 1 address per person.


EDIT: Another way to do this using top that has not been shown by others:

select p.fname, p.lname, a.state, a.country
from person p
join address a on a.addressid =
    (select top 1 a2.addressid
    from address a2
    where a2.personid = p.personid)

This should be very efficient as the nested query will short circuit on the first address found for each person.

2
  • Thanks, I found this one the easiest to slot in. It seems to work despite my user/address ids being alphanumeric rather than just numbers. Is there any problem with this method being slow? I suppose it must be doing a second second search for each result being generated.
    – Oliver
    Jul 22, 2011 at 16:14
  • I think that you have to reference the address table twice in your query no matter what. The top select that ypercube has may actually be faster than my exists(). However, it is hard to tell for sure and I have used this technique many times without noticing too much of a slow down.
    – dana
    Jul 22, 2011 at 21:29
1

Try an aggregate:

SELECT user, address FROM users
JOIN addresses ON (users.user_id = addresses.user_id)
GROUP BY user;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.