我不确定问这个问题的正确方法:我想从一个表中选择一个不同的值并从另一个表中获取值....
$sql1 = mysql_query("SELECT DISTINCT County_ID FROM Customers ORDER BY County_ID ASC") or die(mysql_error());
while($row1 = mysql_fetch_array( $sql1 ))
{
$sql2 = mysql_query("SELECT County_Value FROM Counties") or die(mysql_error());
while($row2 = mysql_fetch_array( $sql2 ))
{
echo "Listed Counties : ".$row2['County_Value']." - id : ".$row1['County_ID']."<br>";
}
}
但这样做我得到了ORDER BY County id,这样做的正确方法是什么,ASC中的值列表是什么?感谢。
$sql1 = mysql_query("SELECT DISTINCT County_ID, County_Value FROM Customers, Counties WHERE Counties.County_ID=Customer.County_ID ORDER BY County_Value ASC") or die(mysql_error());
PS:我应该说我想从customers表中获取一个列出列表的列表,但它们存储为来自县表的id,所以我只想要不同的countie_values ASC
答案 0 :(得分:0)
也许是这样的: -
SELECT CustomersSub.County_ID, County_Value
FROM (SELECT DISTINCT County_ID FROM Customers) CustomersSub
INNER JOIN Counties
ON Counties.County_ID = CustomersSub.County_ID
ORDER BY County_Value ASC
编辑 - 或使用聚合函数计算每个县的客户: -
SELECT Counties.County_ID, County_Value, COUNT(Customers.County_ID) AS CustCountyCount
FROM Counties
INNER JOIN Customers
ON Counties.County_ID = Customers.County_ID
GROUP BY Counties.County_ID, County_Value
ORDER BY County_Value ASC