我的表名是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
编辑我的帖子,因为我给的代码不多,这是我的新问题 my new post
答案 0 :(得分:4)
我认为使用group by
和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
还有一件事,永远不要将用户的值直接传递给你的sql语句,因为 SQL Injection 可能容易受到攻击。使用 PDO 或 MYSQLI
使用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);
}
}
?>
这将允许您插入带单引号的记录。
答案 1 :(得分: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)
答案 2 :(得分: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查询只是为了将日期部分拉出表格 - 请使用built-in SQL date & time functions。
此外,这是偏离主题,但您发布的代码看起来像内联SQL。请改用parameterized queries,否则您很容易受到SQL注入攻击。