Php SQL查询,我需要获取一些值
我有两张桌子,一张和二张 表1包含以下字段:Php SQL查询,我需要获取一些值,php,mysql,Php,Mysql,我有两张桌子,一张和二张 表1包含以下字段: id atype adesc aid id aid adesc value_1 value_2 表2包含以下字段: id atype adesc aid id aid adesc value_1 value_2 $query1 = mysql_query("Select DISTINCT atype from table1"); while($row = mysql_fetch_array($query1)){ $atype = $
id
atype
adesc
aid
id
aid
adesc
value_1
value_2
表2包含以下字段:
id
atype
adesc
aid
id
aid
adesc
value_1
value_2
$query1 = mysql_query("Select DISTINCT atype from table1");
while($row = mysql_fetch_array($query1)){
$atype = $row['atype'];
$query2 = mysql_query("Select adesc from table1 where atype='$atype' and aid IN (Select aid from table2 ) order by id asc");
while($row2 = mysql_fetch_array($query2)){
// i know query2 can only get adesc, so i need value_1 and value_2 in this
echo $row2['adesc'] .'>> '. (this should be value1 from table2) .'>> '. (this should be value2 from table2);
}
}
我还想得到
值_1
和值_2
。任何帮助都将不胜感激
编辑:
表1值在我的数据库中(分别为atype、aid和adesc): 表2中的值(分别为aid、adesc、val1和val2): 我真正想表达的是:
type1
(sum)value_1 (sum)value_2
type2
(sum)value_1 (sum)value_2
type3
(sum)value_1 (sum)value_2
type4
(sum)value_1 (sum)value_2
此SQL查询应生成所需的结果:
select adesc,
value_1,
value_2
from table1
where atype='$atype' and
aid IN (Select aid from table2 )
order by id asc
在SQL中使用一个简单的innerjoin,而不是两个选择:
select table1.adesc,atable2.value1 from table1,table2 where table2.adesc=table1.adesc and table1.aid=table2.aid order by table1.aid asc
编辑:
upd:
$sql=就这样-Connor基于内部连接编写了整个代码。“table2.adesc=table1.adesc”源代码中未指定此条件code@int2000很明显,他们并没有考虑我该如何付款。请查看我的编辑信息以了解详细信息。显然,他们没有考虑我应该如何显示它。请查看我的编辑信息以了解详细信息。thx对于您的更新伙伴,我现在少了1个无忧:D thx很多。。谢谢我真的希望,$atype
永远不会是“Jade的类型”
。
select table1.adesc,atable2.value1 from table1,table2 where table1.aid=table2.aid order by table1.aid asc
$query2 = mysql_query("Select t1.adesc, t2.value_1, t2.value_2 from table1 as t1, table2 as t2 where t1.atype='$atype' and t1.aid = t2.aid order by t1.id asc");
while($row2 = mysql_fetch_array($query2)){
// i know query2 can only get adesc, so i need value_1 and value_2 in this
echo $row2['adesc'] .'>> '. $row2['value_1'] .'>> '. $row2['value_2'];
}
$sql = <<<SQL
select t1.adesc, sum(t2.value_1) as v1, sum(t2.value_2) as v2
from
table1 as t1,
table2 as t2
where
t1.aid = t2.aid
group by t1.atype
order by t1.atype asc
SQL;
$query = mysql_query($sql);
while($row = mysql_fetch_array($query2)){
// i know query2 can only get adesc, so i need value_1 and value_2 in this
echo $row['adesc'] .'>> '. $row['v1'] .'>> '. $row['v2'];
}