2015-12-01 47 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