帮助复杂的mysql查询

时间:2011-09-20 18:21:54

标签: mysql

我有一个我需要添加的现有mysql查询,我不知道该怎么做。

这是我当前的SQL查询。

SELECT tbl_brokerage_names.brokerage_id, tbl_brokerage_names.short_name,
    b.indication, b.max_indication
  FROM tbl_brokerage_names 
  LEFT JOIN (
    SELECT * FROM tbl_recommendation_brokerages
    WHERE recommendation_id = {$_GET['id']}
  ) b ON (tbl_brokerage_names.brokerage_id = b.brokerage_id) 
ORDER BY tbl_brokerage_names.short_name ASC

以下是我需要处理上一个查询的查询。

 SELECT * , COUNT( * )
   FROM tbl_streetaccounts
   JOIN tbl_brokerage_names
 WHERE tbl_brokerage_names.brokerage_id = tbl_streetaccounts.brokerage_id

基本上我需要返回一个计数,所以我需要结合这两个查询。

2 个答案:

答案 0 :(得分:1)

您应该将它们作为两个单独的查询运行。

COUNT(*)查询将返回单行,因此在保留第一个查询的多行结果时,无法将其与第一个查询“组合”。

此外,当您SELECT *, COUNT(*)时,您将从某个任意行获取列。


顺便说一下,你有一个明显的SQL injection漏洞。不要直接在SQL查询中插入$_GET个参数。相反,将其强制转换为整数:

<?php
$id = (int) $_GET['id'];
$sql = "SELECT ... WHERE recommendation_id = {$id}";

答案 1 :(得分:0)

就像@Bill说的那样,如果没有非常奇怪的语法,你就无法获得每一行的计数,但是你可以使用GROUP BY ... WITH ROLLUP获得整体计数。

e.g:

<?php
$id = mysql_real_escape_string($_GET['id']); //works with anything, not just numbers
$query = "
  SELECT tbl_brokerage_names.brokerage_id
         , tbl_brokerage_names.short_name
         , b.indication
         , b.max_indication
         , count(*) as rowcount 
    FROM tbl_brokerage_names 
    LEFT JOIN (
      SELECT * FROM tbl_recommendation_brokerages
      WHERE recommendation_id = '$id'  //The single quotes are essential for safety!
    ) b ON (tbl_brokerage_names.brokerage_id = b.brokerage_id) 
  GROUP BY tbl_brokerage_names.brokerage_id WITH ROLLUP
  ORDER BY tbl_brokerage_names.short_name ASC
";

GROUP BY .. WITH ROLLUP将为结果添加一条额外的行,非聚合列的所有NULL和总计数。

如果你有rowcount > 0的任何行,那么你需要在表b中添加额外的子句到group by子句,以防止MySQL隐藏任意行。
tbl_brokerage_names已经完全定义,因为您按主键分组。