Skip to content

Instantly share code, notes, and snippets.

@dgouldin
Created April 10, 2012 18:08
Show Gist options
  • Save dgouldin/2353330 to your computer and use it in GitHub Desktop.
Save dgouldin/2353330 to your computer and use it in GitHub Desktop.
CREATE TABLE `foo` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`name` varchar(255) NOT NULL
);
CREATE TABLE `bar` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`name` varchar(255) NOT NULL,
`foo_id` integer NOT NULL
);
INSERT INTO foo(id, name) values (1, 'Foo 1');
INSERT INTO foo(id, name) values (2, 'Foo 2');
INSERT INTO foo(id, name) values (3, 'Foo 3');
INSERT INTO bar(id, name, foo_id) values(1, 'Bar 1', 1);
INSERT INTO bar(id, name, foo_id) values(3, 'Bar 3', 3);
SELECT foo.id, foo.name, (bar.id is not null) as bar_exists
FROM foo LEFT OUTER JOIN bar ON foo.id = bar.foo_id
WHERE bar.id is null OR bar.name = 'Bar 3';
SELECT foo.id, foo.name, (bar.id is not null) as bar_exists
FROM foo LEFT OUTER JOIN bar ON foo.id = bar.foo_id AND bar.name = 'Bar 3';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment