2012-06-26 67 views
0

我想要做的是查询一个表,其中包含关于某人的自定义数据并将其存入字段,但是我将每个单独的字段都记录在我的返回中。MySQL - 将记录合并到字段中

我使用的是当前语句是

SELECT s.fname, s.lname, s.email, s.mobile, s.country, cf.name, ca.value FROM 
standard AS s 
INNER JOIN people AS p ON 
(s.pid = p.pid) 
INNER JOIN custom_answers AS ca ON 
(ca.pid = p.pid) 
INNER JOIN custom_fields AS cf ON 
(cf.fieldid = ca.fieldid) 
WHERE p.acctid = 'xxxxxxxxxx' 

这给出22000行的一个结果,而我只是在寻找900行。

数据输出的一个例子是

fname | lname | email | mobile | country | name  | value 
tom | smith | [email protected] | 0412 | AU  | state | Vic 
tom | smith | [email protected] | 0412 | AU  | position | Dept Head 
tom | smith | [email protected] | 0412 | AU  | guest | John Smith 
mick | jones | [email protected] | 0411 | AU  | postnom | AOC 
mick | jones | [email protected] | 0411 | AU  | state | NSW 
mick | jones | [email protected] | 0411 | AU  | postcode | 2000 

而我会它想输出是

fname | lname | email | mobile | country | state | position | guest  | postnom | postcode 
tom | smith | [email protected] | 0412 | AU  | Vic | Dept Head | John Smith | null | null 
mick | jones | [email protected] | 0411 | AU  | NSW | null  | null  | AOC  | 2000 

什么可能会或可能不会导致复杂的是,自定义字段的量ISN”每个人都一样。有些可能只有少数或自定义字段,但有些可能有30个以上。

回答

0

如果我正确理解您的问题,我认为以下结构将起作用。这是我用来从与用户表分开的表中获得学校附属机构和腰带级别的原因。

编辑:这是为已知数量的关联和皮带等级,我不知道如何修改它的未知数量的选项,并调整外部连接。

 SELECT test.tbl_user_accounts.*, t2.org_name as affil_one, t3.org_name as affil_two, t4.rank_name as rank_name 
     FROM test.tbl_user_accounts 
     OUTER JOIN (test.tbl_organizations as t2) ON 
     (t2.org_id = test.tbl_user_accounts.affiliation_one) 
     OUTER JOIN (test.tbl_organizations as t3) ON 
     (t3.org_id = test.tbl_user_accounts.affiliation_two) 
     OUTER JOIN (test.tbl_ranks as t4) ON 
     (t4.id_rank = test.tbl_user_accounts.user_rank); 
+1

答案需要提高以使用外部连接,因为并不是每个用户都表示每个自定义字段。 – dbenham

+0

@dbenham,谢谢。连接仍然让我有些不解。 – JohnP

0

你必须通过申请一组,由所有非聚集,这将创建一个卷起来......所以,将基于比较“cf.name”值MAX()到每个元素,你只会得到每个“as”列的值...如果没有找到这样的记录,它将保持空白(我留下空白空间,但你可以做NULL ...

SELECT 
     s.fname, 
     s.lname, 
     s.email, 
     s.mobile, 
     s.country, 
     MAX(if(cf.name = 'state', ca.value, '   ')) as State, 
     MAX(if(cf.name = 'position', ca.value, '   ')) as Position, 
     MAX(if(cf.name = 'guest', ca.value, '   ')) as Guest, 
     MAX(if(cf.name = 'postnom', ca.value, '   ')) as PostNom, 
     MAX(if(cf.name = 'postcode', ca.value, '   ')) as PostCode 
    FROM 
     standard AS s 
     INNER JOIN people AS p 
      ON s.pid = p.pid 
      INNER JOIN custom_answers AS ca 
       ON p.pid = ca.pid 
       INNER JOIN custom_fields AS cf 
        ON ca.fieldid = cf1.fieldid 
    WHERE 
     p.acctid = 'xxxxxxxxxx' 
    group by 
     s.fname, 
     s.lname, 
     s.email, 
     s.mobile, 
     s.country