如果ENUM等于Y,则选择行,然后从另一个表中选择

时间:2014-02-11 01:20:03

标签: mysql enums case-when

嘿伙计们,我试过把它扔到sqlfiddle上,但看起来好像他们已经疯狂了

我有像这样的表结构

CREATE TABLE `parent` (
  `id`     int(10)             UNSIGNED NOT NULL AUTO_INCREMENT,
  `data`   varchar(32)         DEFAULT NULL,
   PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;


INSERT INTO parent SET data = 'some text';


CREATE TABLE `switch_test` (
  `id`     int(10)             UNSIGNED NOT NULL AUTO_INCREMENT,
  `aid`    int(10)             UNSIGNED NOT NULL,
  `foo`    enum('Y', 'N')      NOT NULL DEFAULT 'N',
  `bar`    enum('Y', 'N')      NOT NULL DEFAULT 'N',
  `baz`    enum('Y', 'N')      NOT NULL DEFAULT 'N',
   PRIMARY KEY (`id`),
   FOREIGN KEY (`aid`) REFERENCES parent(`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;


INSERT INTO switch_test SET aid = 1, foo = 'Y', bar = 'N', baz = 'Y';


CREATE TABLE `switch_items` (
  `id`     int(10)             UNSIGNED NOT NULL AUTO_INCREMENT,
  `sid`    int(10)             UNSIGNED NOT NULL,
  `footxt` varchar(32)         NOT NULL,
  `bartxt` varchar(32)         NOT NULL,
  `baztxt` varchar(32)         NOT NULL,
   PRIMARY KEY (`id`),
   FOREIGN KEY (`sid`) REFERENCES parent(`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;


INSERT INTO switch_items SET aid = 1, footxt = 'foo', bartxt = 'bar', baz = 'baz';

我要做的是设置一个案例,如果我的ENUM等于Y,我想从switch_test中选择该行,然后从switch_test中选择相应的文本语句。如果ENUM 等于Y(又名N),我想选择NEITHER。据我所知,这是非常复杂的,所以我会去那些真正知道如何使这项工作的人。我对这个数据的选择的预期输出在这里给我看这样的东西

+----+-----+-----+--------+-----+--------+
| id | aid | foo | footxt | baz | baztxt |
+----+-----+-----+--------+-----+--------+
|  1 |   1 | Y   | foo    | Y   | baz    |
+----+-----+-----+--------+-----+--------+

我确信这对于一个真正的MYSQL主人来说很容易,但它有点超过我的头脑,这是我不太勇敢的尝试进入第一阶段(获得ENUM Y)

SELECT p.id, 
 CASE
 IF t.foo = 'Y' THEN t.foo AND i.footxt,
 IF t.bar = 'Y' THEN t.bar AND i.bartxt,
 IF t.baz = 'Y' THEN t.baz AND i.baztxt
 FROM parent p, switch_test t, switch_items i, 
 WHERE p.id = t.aid AND p.id = i.sid

它当然不起作用=(

0 个答案:

没有答案