MySQL query problem

Posted by Luke on Stack Overflow See other posts from Stack Overflow or by Luke
Published on 2011-01-05T21:40:47Z Indexed on 2011/01/05 21:54 UTC
Read the original article Hit count: 151

Filed under:
|
|

Ok, I have the following problem.

I have two InnoDB tables: 'places' and 'events'. One place can have many events, but event can be created without entering place. In this case event's foreign key is NULL.

Simplified structure of the tables looks as follows:

CREATE TABLE IF NOT EXISTS `events` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8_bin NOT NULL,
  `places_id` int(9) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_events_places` (`places_id`),
) ENGINE=InnoDB;
ALTER TABLE `events`
  ADD CONSTRAINT `events_ibfk_1` FOREIGN KEY (`places_id`) REFERENCES `places` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION;

CREATE TABLE IF NOT EXISTS `places` (
  `id` int(9) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8_bin NOT NULL,
  PRIMARY KEY (`id`),
) ENGINE=InnoDB;

Question is, how to construct query which contains name of the event and name of the corresponding place (or no value, in case there is no place assigned?).

I am able to do it with two queries, but then I am visibly separating events which have place assigned from the ones that are without place.

Help really appreciated.

© Stack Overflow or respective owner

Related posts about mysql

Related posts about query