MySQL Forums
Forum List  »  Newbie

Re: Query
Posted by: Barry Galbraith
Date: February 09, 2017 09:47PM

Your structure is a type called "EAV" or Entity, Attribute, Value which is notoriously hard to use, as you have discovered with your trivial example.

Much better to build your database like this. It's MUCH easier to query, and easier to add more "attributes" as your requirement evolves over time.

/*Table structure for table `colour` */

DROP TABLE IF EXISTS `colour`;

CREATE TABLE `colour` (
  `c_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `colour` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`c_id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

/*Data for the table `colour` */

insert  into `colour`(`c_id`,`colour`) values 

(1,'red'),

(2,'orange'),

(3,'yellow'),

(4,'green'),

(5,'blue'),

(6,'indigo'),

(7,'violet'),

(8,'black'),

(9,'white');

/*Table structure for table `vehicle` */

DROP TABLE IF EXISTS `vehicle`;

CREATE TABLE `vehicle` (
  `v_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `c_id` int(11) unsigned DEFAULT NULL,
  `w_id` int(11) unsigned DEFAULT NULL,
  PRIMARY KEY (`v_id`),
  KEY `fk_weight` (`w_id`),
  KEY `fk_colour` (`c_id`),
  CONSTRAINT `fk_colour` FOREIGN KEY (`c_id`) REFERENCES `colour` (`c_id`),
  CONSTRAINT `fk_weight` FOREIGN KEY (`w_id`) REFERENCES `weight` (`w_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

/*Data for the table `vehicle` */

insert  into `vehicle`(`v_id`,`name`,`c_id`,`w_id`) values 

(1,'car',4,1),

(2,'car',8,NULL),

(3,'plane',NULL,3),

(4,'boat',NULL,1);

/*Table structure for table `weight` */

DROP TABLE IF EXISTS `weight`;

CREATE TABLE `weight` (
  `w_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `weight` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`w_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

/*Data for the table `weight` */

insert  into `weight`(`w_id`,`weight`) values 

(1,'light'),

(2,'medium'),

(3,'heavy');

mysql> SELECT v.name
    -> FROM vehicle v
    -> JOIN colour c
    -> ON v.c_id =  c.c_id
    -> JOIN weight w
    -> ON v.w_id = w.w_id
    -> WHERE (c.colour = 'green' OR c.colour = 'black')
    -> AND w.weight = 'light';
+------+
| name |
+------+
| car  |
+------+
1 row in set (0.00 sec)

Good luck,
Barry.

Options: ReplyQuote


Subject
Written By
Posted
February 09, 2017 04:41PM
Re: Query
February 09, 2017 09:47PM
February 10, 2017 02:55AM
February 10, 2017 12:22PM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.