Jump to content

[SOLVED] DB design question


webweever

Recommended Posts

I currentyl have 2 table:

thing = thing_id, name, street, city, state, zip, etc...

category = cat_id, cat_name

 

When I created the tables I didnt think about the fact that each thing could belong to multiple categories. My question is how can I change this thing so that I can have a thing that belongs to more than one category. Currently I'm displaying results by SELECTing name, street from thing where cat_name = whatever.

 

Any ideas?

 

Link to comment
https://forums.phpfreaks.com/topic/159386-solved-db-design-question/
Share on other sites

Hi

 

Strictly speaking you wouldn't even need to have them as foreign keys (recommended though).

 

However as an example, assuming the table structures above the following would give you all the categories an item belongs to.

 

SELECT a.name, c.cat_name

FROM thing a

JOIN thing_categories b ON a.thing_id = b.thing_id

JOIN category c ON b.cat_id = c.cat_id

 

All the best

 

Keith

Below is how my DB is setup but I can't get any results with this SELECT statement (SELECT * FROM markers JOIN marker_category ON markers.marker_id = marker_category.marker_id JOIN category ON marker_category.cat_id = category.cat_id)

 

CREATE TABLE IF NOT EXISTS `category` (
  `cat_id` int(11) NOT NULL AUTO_INCREMENT,
  `cat_name` varchar(100) NOT NULL,
  PRIMARY KEY (`cat_id`),
  UNIQUE KEY `cat_id` (`cat_id`,`cat_name`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

CREATE TABLE IF NOT EXISTS `markers` (
  `marker_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(200) NOT NULL,
  `street` varchar(200) NOT NULL,
  `city` varchar(100) NOT NULL,
  `state` varchar(100) NOT NULL,
  `zip` int(11) NOT NULL,
  `url` varchar(200) NOT NULL,
  `lat` float(10,6) NOT NULL,
  `lng` float(10,6) NOT NULL,
  PRIMARY KEY (`marker_id`),
  UNIQUE KEY `marker_id` (`marker_id`,`url`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=29 ;

CREATE TABLE IF NOT EXISTS `marker_category` (
  `marker_id` int(11) NOT NULL,
  `cat_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 

Any ideas?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.