我正在尝试编写一个有点复杂的MySQL查询,它将计算一列中列出的与其他条件相关的不同项目。
目前,该列中的唯一项目是:MC,SR,MP和EV。
这段代码确实有效,但我的问题是,有更好更有效的方法吗?另外,添加到列中的新项目怎么样?
$sql = "Select ps.id, ps.primary_skill,
count(*)
(select COUNT(*)
from items i, item_primary_skill_map ipsm
where i.id = ipsm.item_id
and ipsm.skill_id = ps.id
and i.itemType = 'MC') as mc_count,
(select COUNT(*)
from items i, item_primary_skill_map ipsm
where i.id = ipsm.item_id
and ipsm.skill_id = ps.id
and i.itemType = 'SR') as sr_count,
(select COUNT(*)
from items i, item_primary_skill_map ipsm
where i.id = ipsm.item_id
and ipsm.skill_id = ps.id
and i.itemType = 'MP') as mp_count,
(select COUNT(*)
from items i, item_primary_skill_map ipsm
where i.id = ipsm.item_id
and ipsm.skill_id = ps.id
and i.itemType = 'EV') as ev_count,
(select COUNT(*)
from items i, item_primary_skill_map ipsm
where i.id = ipsm.item_id
and ipsm.skill_id = ps.id
and i.dok = '1') as dok1,
(select COUNT(*)
from items i, item_primary_skill_map ipsm
where i.id = ipsm.item_id
and ipsm.skill_id = ps.id
and i.dok = '2') as dok2,
(select COUNT(*)
from items i, item_primary_skill_map ipsm
where i.id = ipsm.item_id
and ipsm.skill_id = ps.id
and i.dok = '3') as dok3,
(select COUNT(*)
from items i, item_primary_skill_map ipsm
where i.id = ipsm.item_id
and ipsm.skill_id = ps.id
and i.dok = '4') as dok4
FROM primary_skills ps
where grade = '$pl' and subject='$subject'
";
答案 0 :(得分:0)
你可以试试这个: -
Select ps.id, ps.primary_skill, count(*),
CASE i.itemType = 'MC' THEN COUNT(*) END AS as mc_count,
CASE i.itemType = 'SR' THEN COUNT(*) END AS as sr_count,
CASE i.itemType = 'MP' THEN COUNT(*) END AS as mp_count,
CASE i.itemType = 'EV' THEN COUNT(*) END AS as ev_count,
CASE i.dok = '1' THEN COUNT(*) END,
CASE i.dok = '2' THEN COUNT(*) END,
CASE i.dok = '3' THEN COUNT(*) END,
CASE i.dok = '4' THEN COUNT(*) END
from items i, item_primary_skill_map ipsm
where i.id = ipsm.item_id
and ipsm.skill_id = ps.id FROM
and grade = '$pl'
and subject='$subject'
我认为这是解决问题的方法。
答案 1 :(得分:0)
怎么样
select i.itemType, count(*)
from items i, item_primary_skill_map ipsm, primary_skills ps
where i.id = ipsm.item_id
and ipsm.skill_id = ps.id
and ps.grade = '$pl'
and ps.subject = '$subject'
group by i.itemType;
不同之处在于,此查询每个唯一值返回1行,而不是查询中的1列。对于i.dok你需要做同样的事情。
答案 2 :(得分:0)
我提出的解决方案使用循环:
$sql = "Select ps.id, ps.primary_skill ";
foreach ($iTypes as $type){
$sql .=", (select COUNT(*)
from items i, item_primary_skill_map ipsm
where i.id = ipsm.item_id
and ipsm.skill_id = ps.id
and i.itemType = '$type') as " . strtolower($type) . "_count ";
}
$sql .= "FROM primary_skills ps
where grade = '$pl' and subject='$subject'";
感谢您的所有回复。