mySQL结合了多个查询

时间:2018-02-01 13:00:04

标签: php sql

我在PHP网站/游戏中运行一些sql代码,以便在线查找玩家朋友和敌人。两者都从同一个表中提取数据。

// friends online
SELECT COUNT(*) FROM contacts c 
    INNER JOIN online o ON o.playerID = c.playerID 
    WHERE c.myID=".$id." AND c.type='friends'

// enemies online
SELECT COUNT(*) FROM contacts c 
    INNER JOIN online o ON o.playerID = c.playerID 
    WHERE c.myID=".$id." AND c.type='enemies'

有没有办法将这些组合在一起并在最后得到两个计数?会更快吗?

2 个答案:

答案 0 :(得分:3)

使用条件聚合。一般形式是:

SELECT SUM(CASE WHEN c.type = 'friends' THEN 1 ELSE 0 END) as num_friends,
       SUM(CASE WHEN c.type = 'enemies' THEN 1 ELSE 0 END) as num_enemies       
FROM contacts c INNER JOIN
     online o 
     ON o.playerID = c.playerID 
WHERE c.myID = ".$id."; 

是的,这比两个查询更快。如果您有很多类型,可以添加AND type in ('friends', 'enemies')

您的查询未使用online表,除非它用于过滤。如果没有必要,请将其从查询中删除。

答案 1 :(得分:2)

这将产生类型和计数:

type  count
friends  0
enemies   2


select c.type, COUNT(*) as 'count' FROM contacts c 
    INNER JOIN online o ON o.playerID = c.playerID 
    WHERE c.myID=".$id." AND c.type in ('friends','enemies')
group by c.type;