3

我的目标是填充几个子类(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    

我不知道为什么。尝试了不同的东西,但这就是我想出的。有人有想法吗?

编辑:澄清了这篇文章并使其更直接。

4

3 回答 3

2

I think the problem that you are facing is the collision of names in the query. That is, there are multiple columns with the same name and MySQL chooses one of them for the result.

You need to alias the column names for each of the tables to a different name, for example, a_created, b_created, etc.

于 2013-08-23T13:36:00.463 回答
1

This appears to be the classic case where you need to move your where into the join itself so that it doesn't block everything else:

SELECT
    A.*,
    B.*,
    C.*,
    D.*,
    E.*,
    F.*,
    FROM A
    LEFT JOIN B ON A.id = B.id
    LEFT JOIN C ON A.id = C.id
    LEFT JOIN D ON A.id = D.id
    LEFT JOIN E ON A.id = E.id
    LEFT JOIN F ON A.id = F.id
    LEFT JOIN G ON B.myfield = G.myfield and G.anotherfield IN (myvalue1)
    LEFT JOIN H ON C.myfield = H.myfield;
于 2013-08-23T13:35:23.017 回答
1
SELECT a.id, a.type, a.created, b.myfield, b.myotherfield FROM `A` AS a INNER JOIN `B` AS b ON a.id = b.id ;

使用它它必须工作正常。如果您有额外的 where 查询,您可以添加它。

于 2013-08-23T13:52:22.033 回答