我要做的是查询一个包含有关某人的自定义数据并将其输入字段的表格,但是我将每个字段作为记录返回。
我正在使用的当前声明是
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个。
答案 0 :(得分: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 :(得分:0)
你必须通过所有非聚合来应用一个组,这将创建一个汇总...所以应用MAX()基于将“cf.name”值与每个元素进行比较,你只能获得每个“as”列的值...如果没有找到这样的记录,它将保持空白(我留下空格,但你可以做空......
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