2013-06-28 34 views
1

我加載使用id =「3」連接查詢,同時加載評論

$get_comments = mysql_query("SELECT * FROM products_comments WHERE product_id = '3'"); 

現在我想添加「舉報濫用行爲」選項爲每個評論產品的意見,爲此,我有另一個表格爲「abuse_reports」,其中用戶濫用報告將存儲在該表格中,現在如果用戶報告了評論,則report abuse選項不應該在那裏用於該用戶的評論,因爲我正在這樣做:

while($row = mysql_fetch_array($get_comments)){ 
    echo blah blah blah // comment details 
    // now for checking if this user should be able to report this or not, i make this query again: 
    $check_report_status = mysql_query("SELECT COUNT(id) FROM abuse_reports WHERE reporter_user_id = '$this_user_id' AND product_id = 'this_product_id'"); 
    // blah blah count the abuse reports which the current user made for this product 
    if($count == 0) echo "<a>report abuse</a>"; 
} 

有了上面的代碼,對於每個評論我做了一個新的闕ry,這顯然是錯誤的,我應該如何加入第一個查詢?

謝謝

回答

1

更新的查詢數(即現在的工作,通過提問COMMITED)

SELECT pc. * , count(ar.`id`) AS `abuse_count` 
FROM `products_comments` pc 
LEFT OUTER JOIN `abuse_reports` ar ON pc.`id` = ar.`section_details` 
AND ar.`reporter_id` = '$user_id' 
WHERE pc.`product_id` = '$product_id' 
GROUP BY pc.`id` 
LIMIT 0 , 30 

查詢工作如下:您選擇products_comments的所有字段與給定的product_id,但您也計算給定product_idabuse_reports的條目。現在你LEFT JOINabuse_reports,這意味着你訪問該表並將它掛在左邊(您的products_comments表)。外允許,沒有必要在abuse_reports表中的值,所以如果沒有報告,你會得到空的,因此0

計數請仔細閱讀本: 不過,我需要組結果,否則你只會得到一個合併的行作爲結果。因此,請將products_comments擴展爲int類型的字段comment_idprimary key並且具有auto_increment

UPDATE:濫用計數 現在你可以做兩件事情:通過在結果循環,您可以爲每個單獨的元素看是否有報道由用戶或沒有(這樣你可以隱藏的濫用報告鏈接例如)。如果你想要報告的總數,你只需增加一個你在循環外部聲明的計數器變量。就像這樣:

$abuse_counter = 0; 
while($row = mysql....) 
{ 
    $abuse_counter += intval($row['abuse_count']); // this is 1 or 0 
    // do whatever else with that result row 
} 

echo 'The amount of reports: '.$abuse_counter; 

只是一種原始的樣品

+0

這不會加載任何評論product_id = 3 – behz4d

+0

對不起,我已經更新了我上面的答案中的查詢 - 它現在起作用了,我自己測試了它。這是'WHERE'子句中的一個錯誤,因爲'reporter_user_id'可能並不總是可用的(所以它必須位於'ON'部分中)。希望它現在適合你,請讓我知道;) – Francodi

+0

似乎有什麼不對勁,它只是加載1條評論,而對於product_id = 3有超過10條評論,而對於其他產品則不加載! – behz4d

0

我相信你正在尋找一個像這樣的查詢。

SELECT pc.*, COUNT(ar.*) 
FROM products_comments AS pc 
LEFT JOIN abuse_reports AS ar ON reporter_user_id = pc.user_id AND ar.product_id = pc.product_id 
WHERE product_id = '3'" 
0

試試這個SQL

SELECT pc.*, COUNT(ar.id) AS abuse_count 
FROM products_comments pc 
     LEFT JOIN abuse_reports ar ON pc.product_id = ar.product_id 
WHERE pc.product_id = '3' AND ar.reporter_user_id = '$this_user_id' 
GROUP BY pc.product_id 

結果是abuse_reports products_comments的列表中,如果存在reporter_user_id

+0

的結果應該是的product_id = 3的所有意見,並有機會獲得由該用戶提交該產品報告虐待行爲的數量,這是不工作... – behz4d