SQL多行计数

时间:2014-12-15 11:46:00

标签: mysql sql

有没有办法避免将查询数乘以在不同表中进行多次行计数。 我有一个id(来自之前的请求 - ID_roster)。有了这个id,我需要在许多表中检查显示徽章的行数:

// Get number of MEMBERS in the roster  
    $stmt = $mysqli->prepare("SELECT COUNT(id_membre) 
                                FROM roster_par_membre 
                                WHERE ID_roster = ?");
$stmt->bind_param('i', $id_roster);  
$stmt->execute(); 
$stmt->store_result();
$stmt->bind_result($nombre_membre);
$stmt->fetch(); 

然后(对另一个表几乎相同的查询)

// Get number of pending requests for this roster
    $stmt = $mysqli->prepare("SELECT COUNT(id_membre) 
                                FROM roster_join_request
                                WHERE ID_roster = ?");
$stmt->bind_param('i', $id_roster);  
$stmt->execute(); 
$stmt->store_result();
$stmt->bind_result($nombre_roster_request);
$stmt->fetch(); 

所以有9张桌子;看起来相当复杂。有更有效的方法吗? 欢呼声

2 个答案:

答案 0 :(得分:3)

您可以使用union allcross join来合并查询。例如:

(SELECT 'roster_par_membre' as which, COUNT(id_membre) 
 FROM roster_par_membre 
 WHERE ID_roster = ?
) UNION ALL
(SELECT 'roster_join_request', COUNT(id_membre) 
 FROM roster_join_request
 WHERE ID_roster = ?
)

(依此类推。)

这将为每个表生成一行。第一列是表名(称为which),第二列是计数。

答案 1 :(得分:1)

如果您愿意,可以将union all与表名一起使用 这是一个生成SQL的python代码:

TABLES = ['t1', 't2', 't3', 't4', 't5', 't6', 't7', 't8']
sql = "SELECT %(table_name)s, COUNT(id_membre) FROM %(table_name)s WHERE ID_roster = ?"
 full_sql = '\nUNION ALL\n'.join([sql % {'table_name': t} for t in TABLES])

print full_sql
SELECT t1, COUNT(id_membre) FROM t1 WHERE ID_roster = ?
UNION ALL
SELECT t2, COUNT(id_membre) FROM t2 WHERE ID_roster = ?
UNION ALL
SELECT t3, COUNT(id_membre) FROM t3 WHERE ID_roster = ?
UNION ALL
SELECT t4, COUNT(id_membre) FROM t4 WHERE ID_roster = ?
UNION ALL
SELECT t5, COUNT(id_membre) FROM t5 WHERE ID_roster = ?
UNION ALL
SELECT t6, COUNT(id_membre) FROM t6 WHERE ID_roster = ?
UNION ALL
SELECT t7, COUNT(id_membre) FROM t7 WHERE ID_roster = ?
UNION ALL
SELECT t8, COUNT(id_membre) FROM t8 WHERE ID_roster = ?