1

我的表名是ads这样的:

    id    ad_country          ad_gender     ad_birthday
     1     UK                  Male          2012-02-26
     2     sangapor            Female        2011-05-29
     3     UK                  Female        2010-04-12

我有两个下拉选择选项

   one  is to select country

    one is to select year 

是否可以进行一个仿射结果的 sql 查询以获得:

每个国家有多少男性被选中,也被选中的年份。每个国家和每年有多少女性被选中也thx

我试过这个 sql 但没有用。

    SELECT COUNT(ad_gender) AS male FROM ads  WHERE '".$_POST['country']."' = ad_country  AND ad_gender = Male AND '".$_POST['year']."' = '".$row2['ye']."'

注意 $row2['ye'] 来自 $sql2 如下

     SELECT ad_birthday,(substr(ad_birthday , 1, 4)) AS ye FROM ads

编辑了我的帖子,因为我给的代码不多,这是我的新问题, 我的新帖子

4

3 回答 3

4

我认为使用group byand最简单having的方法是case在查询中使用。

SELECT  SUM(CASE WHEN ad_gender = 'Male' THEN 1 ELSE 0 END) TotalMale,
        SUM(CASE WHEN ad_gender = 'Female' THEN 1 ELSE 0 END) TotalFemale
FROM    ads
WHERE   ad_country = 'countryHere' AND
        YEAR(DATE(ad_birthday)) = yearHere

SQLFiddle 演示

还有一件事,永远不要将用户的值直接传递给您的 sql 语句,因为它可能会受到SQL Injection的攻击。使用PDOMYSQLI

使用 PDO 扩展的示例:

<?php

     $query = "    SELECT   SUM(CASE WHEN ad_gender = 'Male' THEN 1 ELSE 0 END) TotalMale,
                           SUM(CASE WHEN ad_gender = 'Female' THEN 1 ELSE 0 END) TotalFemale
                   FROM     ads
                   WHERE    ad_country = ? AND
                            YEAR(DATE(ad_birthday)) = ?"

    $country = 'UK';
    $year = 2012;
    $dbh = new PDO('mysql:host=localhost;dbname=test;charset=utf8', $user, $pass);
    $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $stmt = $dbh->prepare($query);
    $stmt->bindParam(1, $country);
    $stmt->bindParam(2, $year);
    if ($stmt->execute()) 
    {
         while ($row = $stmt->fetch()) 
         {
              print_r($row);
         }
    }

?>

这将允许您使用单引号插入记录。

于 2012-09-12T00:51:20.233 回答
2
select ad_country, count(case when ad_gender = 'male' then 1 end) male, 
count(case when ad_gender = 'female' then 1 end) female, year(ad_birthday) year
from ads
group by ad_country, year(ad_birthday)
于 2012-09-11T21:16:37.800 回答
2

这应该是一个非常简单的查询来执行,所以我想知道为什么它不适合你。你试过什么了?

select
  ad_country as country,
  YEAR(ad_birthday) as year,
  ad_gender as gender,
  count(id) as count
from ads
where ad_country in ('/* your country params here*/')
group by ad_country, year, ad_gender
having YEAR(ad_birthday) in ('/* your year params here*/')

您不需要第二个 SQL 查询来将日期部分从表中拉出 - 为此使用内置的 SQL 日期和时间函数

此外,这是题外话,但您发布的代码看起来像内联 SQL。请改用参数化查询,否则您很容易受到 SQL 注入攻击。

于 2012-09-11T21:18:33.663 回答