需要一些帮助来创建一个可以获得我想要的结果的查询。
我从mysql数据库中的2个表中提取信息。
TABLE 1 - tblclients
ID firstname lastname
1 Bob K
2 Mary J
3 Tod M
tblcustomfieldsvalues.RelId = tblclients.ID
TABLE 2 - tblcustomfieldsvalues
ID fieldid RelId value
1 15 3 3500
2 15 2 1500
3 17 3 Calp
4 17 2 Amazon
5 17 2 Calp
TABLE 3 - tblcustomfields (JUST FOR REFERENCE)
ID FieldID name
1 15 Purchase Amount
2 17 Site
期望的结果:
我想在第4栏(FieldID = 15)中显示购买金额,其中FieldID = 17且value ='calp'
ID FirstName LastName Value
1 Tod M 3500
2 Mary J 1500
当前查询:
SELECT tblclients.id, tblclients.firstname, tblclients.lastname, tblcustomfieldsvalues.value FROM tblclients INNER JOIN tblcustomfieldsvalues ON tblclients.id = tblcustomfieldsvalues.relid WHERE tblcustomfieldsvalues.fieldid = 17 AND tblcustomfieldsvalues.value = 'Calp'
当前结果:
ID FirstName LastName Value
1 Tod M Calp
2 Mary J Calp
答案 0 :(得分:0)
我不清楚你期待什么结果...... 首先,我确信你写了fieldid = 17来得到这个结果而不是47。 如果是这样 你的结果很正常。你要求fieldid 17并且也值'Calp'。 你想要fieldid 15吗?那些人有价格...... 或者也许
SELECT tblclients.id, tblclients.firstname, tblclients.lastname, tblcustomfieldsvalues.value FROM tblclients INNER JOIN tblcustomfieldsvalues ON tblclients.id = tblcustomfieldsvalues.relid WHERE tblcustomfieldsvalues.fieldid in (15,17) OR tblcustomfieldsvalues.value = 'Calp'
您的查询:
SELECT tblclients.id, tblclients.firstname, tblclients.lastname, tblcustomfieldsvalues.value FROM tblclients INNER JOIN tblcustomfieldsvalues ON tblclients.id = tblcustomfieldsvalues.relid WHERE tblcustomfieldsvalues.fieldid = 47 AND tblcustomfieldsvalues.value = 'Calp'
答案 1 :(得分:0)
一种方法是条件聚合:
select c.*, value15 as value
from tblclients c join
(select cfv.relid,
max(case when fieldid = 15 then value end) as value15,
sum(case when fieldid = 17 and value = 'Calp' then 1 else 0 end) as cnt17
from tblcustomfieldsvalues cfv
group by cfv.relid
) cv
where cnt17 > 0;
您也可以使用连接执行此操作。但是每个字段都需要单独的连接:
SELECT c.id, c.firstname, c.lastname, cfv15.value
FROM tblclients c INNER JOIN
tblcustomfieldsvalues cfv17
ON c.id = cfv17.relid AND
cvf17.fieldid = 17 AND cfv17.value = 'Calp' INNER JOIN
tblcustomfieldsvalues cfv15
ON c.id = cfv15.relid AND
cvf15.fieldid = 15;