我的目标是填充几个子类(B、C、D、E、F...)的几个对象,所有这些对象都扩展了一个父类 A。所有这些,都在一个单一且唯一的大查询中。
假设我有几个反映类结构的表,包括这 3 个:
Table A /* the parent class */
id type created
--------------------------------
392 B 1377084886
Table B /* one of the child classes */
id myfield myotherfield anotherone oneagain
-------------------------------------------------------------
392 234 'foo' 'bar' 3
Table G /* not part of the structure, just here for the query to check a field */
myfield fieldtocheck evenmorefields
------------------------------------------------
234 'myvalue1' 'foobar'
现在:
/* This (the query I want): */
SELECT
a.*,
b.*,
c.*,
d.*,
e.*,
f.*
FROM A a
LEFT JOIN B b ON a.id = b.id
LEFT JOIN C c ON a.id = c.id
LEFT JOIN D d ON a.id = d.id
LEFT JOIN E e ON a.id = e.id
LEFT JOIN F f ON a.id = f.id
LEFT JOIN G g_b ON b.myfield = g_b.myfield
LEFT JOIN G g_c ON c.myfield = g_c.myfield
WHERE g_b.fieldtocheck IN (myvalue1);
/* Returns this (what I don't want): */
id->392
type->B
created->1377084886
myfield->NULL /* why NULL? */
myotherfield->NULL /* why NULL? */
anotherone->NULL /* why NULL? */
oneagain->3 /* why, whereas other fields from B are NULL, is this one correctly filled? */
然而:
/* This (the query I don't want): */
SELECT
a.*,
b.*
FROM A a
LEFT JOIN B b ON a.id = b.id
LEFT JOIN G g_b ON b.myfield = g_b.myfield
WHERE g_b.fieldtocheck IN (myvalue1);
/* Returns this (what I want): */
id->392
type->B
created->1377084886
myfield->234
myotherfield->'foo'
anotherone->'bar'
oneagain->3
我不知道为什么。尝试了不同的东西,但这就是我想出的。有人有想法吗?
编辑:澄清了这篇文章并使其更直接。