views:

56

answers:

2

I had a select box where the user will select the list of cities they travelled. After that the admin will search for the users with particular cities.

I am very confused with the structure of the database. There are totally 300 cities. Creating column for each city and store it with boolean on or off, looks a childish technique. Any one help me plz

A: 

Hi,

You don't have to create a column for each city. You simply create a "City" column, where each row is a city. You then have a "Visited" column, where each row is a boolean. In total, there are only two columns.

City      |   Visited

London    |     1
Paris     |     0 
New York  |     1

etc...

keyboardP
So for each user i had to have seperate table????????????????
Rajasekar
No. Aaronaught has posted a more detailed answer. You need one column called "UserID" which contains a unique identifier for each user and preferably a column for UserName for a more friendly description of the user.
keyboardP
Thanks for ur answer
Rajasekar
+5  A: 

Not sure why you've tagged this both mysql and sql-server - are you using both?

Anyway, this is a standard many-to-many mapping:

Table: User

  • UserID (int, PK)
  • UserName (varchar(50), not null)

Table: City

  • CityID (int, PK)
  • CityName (varchar(50), not null)

Table: UserCity

  • AssociationID (int, PK)
  • UserID (int, FK User, not null)
  • CityID (int, FK City, not null)

To retrieve all of the cities for a given user:

SELECT c.CityID, c.CityName
FROM User u
INNER JOIN UserCity uc
    ON uc.UserID = u.UserID
INNER JOIN City c
    ON c.CityID = uc.CityID
WHERE u.UserID = @UserID
Aaronaught
I've always liked using 'and' clauses instead of joins like so:select c.CityId, c.CityName from User u, City c, UserCity uc where u.UserId = uc.UserId and c.CityId = uc.CityId and u.UserId = @UserIdI find it easier to read, but do you know if this is maybe slower or has any other drawbacks?
Sevas
Thank you very much +1
Rajasekar
@Sevas - Both are valid syntax but the explicit join syntax is the ANSI standard and should work on all DBMS. The implied join is platform-specific (Microsoft and mysql) and harder to write correctly when joining many tables; it's valid, but not commonly used anymore.
Aaronaught
@Aaronaught: Comma-style syntax for *inner* joins is also ANSI standard, supported for the sake of backward compatibility. It's supported by every popular RDBMS. But doing *outer* joins with this syntax uses nonstandard syntax in Oracle, Sybase, and Microsoft SQL Server.
Bill Karwin