2015-12-01 89 views
-7

我有一個問題給你。我認爲這很容易解決,但我非常關注這一點。兩張表之間的查詢?

我有兩個表,一個是產品,另一個是收藏夾。收藏夾表格有2個字段,id_userid_product

現在,我想查詢所有收藏夾產品並在我的網頁上顯示它們。我想我必須對我的查詢做一個join,但目前我真的迷路了。

例如我想用id = 3顯示用戶的所有收藏夾產品,我該怎麼辦?

+2

您是否可以使用表格佈局? –

+0

子查詢或加入。子查詢的例子:'SELECT * FROM products WHERE id IN(SELECT id_product FROM favorites WHERE id_user = 3)' – Steve

回答

3

爲了將來的參考,當在Stack上提出問題時,您需要包含所有相關信息。比如你的數據庫佈局。我們不是讀心者,但這是一個猜測。

Select * from Favorites junk 
Left join Products poop on 
poop.id = junk.id_product 
Left join Users stuff on 
stuff.id = junk.id_user 
1

您正在通過連接尋找這樣的查詢。

select a.* from favourites as a join products as b on a.id_product= b.id 
+0

也許這是解決方案,但我想獲得產品信息,所以這會是這樣的,不是嗎? 'select b。* from products b加入收藏夾a on a.id_product = b.id' –

+0

是的,這就是你的查詢應該是這樣的...所以你會得到每個最喜愛的產品基於產品ID ..done –

0

你需要做的主要查詢對你的「收藏夾」表格並加入產品表,所以假設你id_product場點,在您的產品表中的ID字段:

SELECT fav.*, prod.* FROM favourites fav RIGHT JOIN products prod ON prod.id = fav.id 

注我在這裏使用RIGHT JOIN,因爲你想確保右邊的表(在這種情況下最喜歡的)有信息來檢索(否則如果id_product指向一個不存在的id,你會得到NULL結果)。另請注意,我給每個表分別設置了一個別名(分別爲favprod),因爲這會使查詢更容易/更快速地編寫。

希望這會有所幫助!

0

您可以使用INNER JOIN。

如果你按照下面的例子,你可以得到這個想法。我不知道你的產品表中有什麼。從你的描述看來,你會加入用戶ID。

USE AdventureWorks; 
GO 
/* 
Create a Join on 2 tables to show information from both. The example tables are from the AdventureWorks database: 
    Production.Product 
    Production.ProductInventory 

In this example we'll look to get the Product ID and Name from the Product table and the inventory quantity, shelf, and bin from the  ProductInventory table. 
*/ 

SELECT 
/* Precede each column you want to select with the identifier of which table it's coming from */ 
    prod.ProductID, 
    prod.Name, 
    inv.Shelf, 
    inv.Bin, 
    inv.Quantity 

/* Select items from the Product Table */ 
FROM Production.Product AS prod 

/* Use an INNER JOIN to get the items related to the Product table that are in the ProductInventory table based on the ProductID */ 
INNER JOIN Production.ProductInventory AS inv ON 
    prod.ProductID = inv.ProductID