Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
php+mysql:加總+order by
程式大約解說:$result 是抓出sale的s_goods的值(不重複)帶到$result2, $result2 依照 s_goods的值,抓出s_amount總值排列出來 (請看VCR = =).
問題1:請問我$result2 後面有order by 了 可是他卻不排列 為什麼為這樣?
問題2:我希望解決問題1後,只秀出3筆資料就好,用limit 3?
$result=mysql_query("SELECT distinct s_goods,x1.g_name from sale left join goods x1 on s_goods = x1.g_id");
while($show = mysql_fetch_array($result))
{
$result2=mysql_query("SELECT s_goods,x1.g_name,sum(s_amount) as amount from sale
left join goods x1 on s_goods = x1.g_id
where s_goods = $show[s_goods] group by s_goods order by amount");
while($show2 = mysql_fetch_array($result2))
{
echo "<tr><td>".$show2[g_name]."</td><td>".$show2[amount]."</td></tr>";
}
}
VCR
---------------------------
$show2[g_name] / $show2[amount]
---------------------------
產品1 / 2
產品2 / 4
產品3 / 5
產品4 / 3
---------------------------
目標
---------------------------
$show2[g_name] / $show2[amount]
---------------------------
產品1 / 2
產品4 / 3
產品2 / 4
產品3 / 5
---------------------------
第一個回答: amount 是屬於 sale 的 幹麼要加x1 = =
第二個回答:貼到phpmyadmin中的 sql 試試 看不出來 因為只會秀出一筆 我要的是都秀出來 再排列 要不然我用兩個迴圈 就沒意義了 = =...
不過還是謝謝你 ^^ <希望有經驗的大大 能幫個忙給點意見>
表格 goods
欄位 g_id(key) g_name
範例 1 產品1
表格 sale
欄位 s_goods s_amount
範例
老師好 我把需要用的表格欄位 補充進來
表格 goods
欄位 g_id(PK)(R1) g_name
範例 1 產品1
2 產品2
表格 sale
欄位 s_goods(R1) s_amount
範例 1 5
2 2
1 3
(PS: R1表示連結 )
老師好 我有測試你寫的語法,有錯(下面是錯誤訊息)
#1064 - (SELECT SUM(s_amount) FROM goods AS x1 WHERE x1.g_id=x2.s_g
我試過改看看了 不過 我太弱了 orz
3 Answers
- 小君Lv 41 decade agoFavorite Answer
主要是你的查詢語法不對!
因為你這是兩道查詢,會有兩份資料集,但你又想用第一份資料集帶入第二份資料集,這樣是無法解決你要的排序問題!因為你的$Result2是一筆一筆逐筆查出來的,然後輸出到網頁上,自然不會排序!
因此你必須先在資料庫端一次查詢完並排好序!建議你用子查詢的方式來完成!
SELECT DISTINCT x2.s_goods,x3.g_name,
(SELECT SUM(s_amount) FROM goods AS x1
WHERE x1.g_id=x2.s_goods GROUP BY x1.g_id) AS amount
FROM sale AS x2 LEFT JOIN goods AS x3
on x2.s_goods = x3.g_id ORDER BY amount
這樣應該就能查出你想要的結果後,之後再一一輸出到前端的網頁上!只需要一次的Result即可!
因為我手邊沒有將MySQL灌起來,本人是用SQL Server,中文北風資料庫測試的!
因為MySQL在4~5.0版之後應該可以子查詢了!
P.S 因為不大清楚您的資料表結構,大致上是用你的舊語法改的,若有錯誤,請見諒!
Source(s): 巨匠電腦講師 - 網路礦工Lv 71 decade ago
你的 $result2 只會有 一筆 資料 怎麼 order by
你犯了 邏輯上的錯誤
先把邏輯搞清楚 在去QUERY 你的資料
我整個看 其實你只要一個QUERY
就可以得到你要的結果了
這麼累幹嘛 昏倒 @@
- ?Lv 71 decade ago
別名加上去看看
x1.amount
我亂掰的 懶的看 你參考
2008-01-09 20:18:12 補充:
SELECT s_goods,x1.g_name,sum(s_amount) as amount from sale
left join goods x1 on s_goods = x1.g_id
where s_goods = $show[s_goods] group by s_goods order by amount
貼到phpmyadmin中的 sql 試試
看有沒有錯 也是一種檢查方式
我還是亂掰的 你聽聽就好