开发者

Mysql Select Dynamic column (3 tables)

I am looking for the SQL to do :

And thing about field lis开发者_C百科t must be totally dynamic. I dont want to go change my SQL each time an admin add a field into the fields table.

Table content
    -------------
    CID
    text
    category

    CID | text | category
    ----------------------
    1   | ...  | apple
    2   | ...  | apple
    3   | ...  | apple

    Table fields
    -------------
    FID
    typename

    FID | typename
    ----------------
    1   | field1
    2   | field2
    3   | field3

    Table fields_value
    -------------
    CID
    FID
    value

    CID | FID | value
    -------------------
    1   | 1   | value1
    1   | 2   | value2
    1   | 3   | value3
    2   | 1   | value4
    2   | 2   | value5
    2   | 3   | value6
    3   | 1   | value7
    3   | 2   | value8
    3   | 3   | value9

    #####
    ---> ???? SELECT content.*,...dynamic field.* FROM content WHERE category = "apple" LIMIT 20

    RESULT I AM LOOKING FOR:
    -------------------
    CID | text | category | field1 | field2 | field3 
    -------------------------------------------------
    1   | ...  | apple    | value1 | value2 | value3
    2   | ...  | apple    | value4 | value5 | value6
    3   | ...  | apple    | value7 | value8 | value9


There is no way to do what you want with mysql (have dynamically named columns). The closest you can do is

SELECT CID, text, category, typename, value
  FROM content JOIN fields_value JOIN fields
  WHERE content.CID = fields_value.CID AND fields_value.FID = fields.FID

Which will give you

CID | text | category | typename | value
 1  | ...  | apple    | field1   | value1
 1  | ...  | apple    | field2   | value2
 1  | ...  | apple    | field3   | value3
 2  | ...  | apple    | field1   | value4
 2  | ...  | apple    | field2   | value5
 2  | ...  | apple    | field3   | value6
 3  | ...  | apple    | field1   | value7
 3  | ...  | apple    | field2   | value8
 3  | ...  | apple    | field3   | value9

Of course, you could make a table dynamically by loading the fields table and building a CREATE TABLE command with the fields you want, then populate it from your fields_value table, but that's probably not what you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜