0

我想要做的是查询一个包含关于一个人的自定义数据的表并将其放入字段中,但是我将每个单独的字段作为我的回报中的记录。

我正在使用的当前语句是

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'

这给出了 22,000 行的结果集,而我只寻找 900 行。

数据输出的一个例子是

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

而我希望它输出的是

fname | lname | email | mobile | country | state | position  | guest      | postnom | postcode
tom   | smith | t@t   | 0412   | AU      | Vic   | Dept Head | John Smith | null    | null
mick  | jones | m@j   | 0411   | AU      | NSW   | null      | null       | AOC     | 2000

可能会或可能不会导致复杂化的是,每个人的自定义字段的数量并不相同。有些可能只有少数或自定义字段,但有些可能超过 30 个。

4

2 回答 2

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
于 2012-06-27T02:44:18.457 回答
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);
于 2012-06-27T00:44:14.900 回答