0

我不确定问这个问题的正确方法:我想从一个表中选择一个不同的值并从另一个表中获取值....

$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:我应该说我想从客户表中获取列出的县列表,但它们从县表中存储为 id,所以我只想要不同的 countie_values ASC

4

1 回答 1

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
于 2013-03-12T13:06:13.807 回答