2017-06-12 163 views
0

我正在做的是:提取數據以向用戶顯示產品,以便他/她可以評估產品。使用下面的查詢可以正常工作。使用特定標準從兩個表中提取數據

$query = " SELECT  table_products.product_name, 
         table_products.product_expiry, 
         table_users.name, 
         table_users.email 

      FROM table_products 
      INNER JOIN table_users ON table_users.user_id = table_products.user_id 
      ORDER BY table_users.id DESC"; 

現在我想問的是:如何僅顯示用戶尚未評分的產品。一旦用戶對產品進行評級後,該產品不應再由該用戶的查詢獲取。

我有3個表

table_users (user_id, name, email) 

table_products (product id_, user_id, product_name, product_expiry) 

table_rating (rating_id, user_id, product_id, rating) 

,並希望從2個表

獲取數據
table_users, table_products 

數據中獲取

table_users.name, 
table_users.email, 
table_products.product_name, 
table_products.product_expiry 

如何爲這個任務設置查詢一個具體的used_id

感謝您的時間和幫助:)

回答

0

你可以加入收視率表和統計收視率的數量然後檢查它在where子句中,這樣的事情(未經測試):

$query = "SELECT 
table_products.product_name, 
table_products.product_expiry, 
table_users.name, 
table_users.email, 
count(table_rating.id) as ratings 

FROM table_products 
INNER JOIN table_users ON table_users.user_id = table_products.user_id 
left join table_rating ON table_rating.product_id = table_products.id 

where ratings = 0 
ORDER BY table_users.id DESC"; 
+0

確定。讓我測試,我會回覆你 –

0

有是多種方式,你需要連接表,分組和使用條款,請參考圖像。 enter image description here

0

使用此查詢

SELECT  table_products.product_name, 
         table_products.product_expiry, 
         table_users.name, 
         table_users.email 

      FROM table_products 
      INNER JOIN table_users ON table_users.user_id = table_products.user_id 
      LEFT JOIN table_rating on table_products.product_id=table_rating.product_id 
      WHERE table_rating.product_id IS NULL 
      ORDER BY table_users.id DESC 
+0

嗨。使用你的代碼,我得到1)其他用戶添加的額定產品(不應該被提取)和2)他自己和其他用戶的未評級產品。但我只需要未分級的產品,不管他自己或其他用戶添加 –

0
SELECT  
table_products.product_name, 
table_products.product_expiry, 
table_users.name, 
table_users.email 

FROM table_products 
INNER JOIN table_users ON table_users.user_id = table_products.user_id 

LEFT JOIN table_rating ON table_products.user_id = table_rating.user_id 
AND table_products.product_id = table_rating.product_id 

WHERE table_rating.product_id IS NULL 

ORDER BY table_users.user_id DESC 
+0

嗨@Leandro你的答案非常接近。 –

+0

,但存在一個問題,即其他用戶添加的產品在評級後對current_user也可見。只是那些正在跳過的產品正在被評級的同一用戶發佈。 –

+0

實際上,我想要跳過這兩個評級產品(由評級和其他用戶的同一用戶添加)。我們有該用戶的評級的user_id。我們可以應用它來獲得所需的輸出 –