![](/img/trans.png)
[英]What is the correct way to write a find() statement in CakePHP given a simple select query with ORDER and LIMIT?
[英]What is the query statement to write in order to solve the followin database problem?
我在数据库中有以下 3 个表。
Programs_Table
Program_ID(主键)
开始日期
结束日期
完成了
目标满足
Program_type_ID
Programs_Type_Table (不同类型的节目,支持表格中的下拉列表)
Program_type_ID(主键)
程序名
Program_description
Client_Program_Table
Client_ID(主键)
Program_ID(主键)
找出特定程序(程序类型)中有多少客户的最佳方法是什么?
下面的 SQL 陈述会是最好的方法,甚至是合理的吗?
SELECT Client_ID FROM Client_Program_Table
INNER JOIN Programs_Table
ON Client_Program_Table.Program_ID = Programs_Table.Program_ID
WHERE Programs_Table.Program_type_ID = "x"
其中“x”是我们感兴趣的特定程序的 Program_type_ID。
或者以下是更好的方法吗?
$result = mysql_query("SELECT Program_ID FROM Programs_Table
WHERE Program_type_ID = 'x'");
$row = mysql_fetch_assoc($result);
$ProgramID = $row['Program_ID'];
$result = mysql_query("SELECT * FROM Client_Program_Table
WHERE Program_ID = '$ProgramID'");
mysql_num_rows($result) // returns how many rows of clients we pulled.
提前谢谢你,请原谅我的经验不足和我犯的任何错误。
如果您想知道一个程序中有多少客户,您宁愿使用 COUNT( * )。 MySQL (with MyISAM) 和 SQL Server 有一种快速检索总行数的方法。 使用 SELECT(*),然后 mysql_num_rows 会导致不必要的 memory 资源和计算时间。 对我来说,这是最快的,虽然不是“最干净”的方式来编写你想要的查询:
SELECT
COUNT(*)
FROM
Client_Program_Table
WHERE
Program_ID IN
(
SELECT
Program_ID
FROM
Programs_Table
WHERE
Program_type_ID = 'azerty'
)
这是为什么?
使用 JOIN 使查询更具可读性,但子查询通常被证明计算得更快。
您可以这样做:
<?php
// always initialize a variable
$number_of_clients = 0;
// escape the string which will go in an SQL query
// to protect yourself from SQL injection
$program_type_id = mysql_real_escape_string('x');
// build a query, which will count how many clients
// belong to that program and put the value on the temporary colum "num_clients"
$query = "SELECT COUNT(*) `num_clients` FROM `Client_Program_Table` `cpt`
INNER JOIN `Programs_Table` `pt`
ON `cpt`.`Program_ID` = `pt`.`Program_ID`
AND `pt`.`Program_type_ID` = '$program_type_id'";
// execute the query
$result = mysql_query($query);
// check if the query executed correctly
// and returned at least a record
if(is_resource($result) && mysql_num_rows($result) > 0){
// turn the query result into an associative array
$row = mysql_fetch_assoc($result);
// get the value of the "num_clients" temporary created column
// and typecast it to an intiger so you can always be safe to use it later on
$number_of_clients = (int) $row['num_clients'];
} else{
// query did not return a record, so we have no clients on that program
$number_of_clients = 0;
}
?>
这将返回特定程序类型 (x) 中的客户端计数:
SELECT COUNT(cpt.Client_ID), cpt.Program_ID
FROM Client_Program_Table cpt
INNER JOIN Programs_Table pt ON cpt.Program_ID=pt.Program_ID
WHERE pt.Program_type_ID = "x"
GROUP BY cpt.Program_ID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.