Php 两个表之间的查询?

Php 两个表之间的查询?,php,mysql,sql,join,Php,Mysql,Sql,Join,我有一个问题要问你。我认为这很容易解决,但我对此非常执着 我有两张桌子,一张是产品,另一张是收藏夹。收藏夹表有两个字段,id\u user和id\u product 现在,我想查询所有最喜欢的产品,并将它们显示在我的网页上。我想我必须加入我的查询,但现在我真的迷路了 例如,我想显示id=3的用户的所有收藏夹产品,我应该做什么?为了将来参考,在堆栈上提问时,您需要包括所有相关信息。例如数据库布局。我们不是读心术的人,这里有一个猜测 Select * from Favorites junk Left

我有一个问题要问你。我认为这很容易解决,但我对此非常执着

我有两张桌子,一张是产品,另一张是收藏夹。收藏夹表有两个字段,id\u user和id\u product

现在,我想查询所有最喜欢的产品,并将它们显示在我的网页上。我想我必须加入我的查询,但现在我真的迷路了


例如,我想显示id=3的用户的所有收藏夹产品,我应该做什么?

为了将来参考,在堆栈上提问时,您需要包括所有相关信息。例如数据库布局。我们不是读心术的人,这里有一个猜测

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

您正在寻找这样一个带有联接的查询

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

您需要对Favorites表执行主查询并连接products表,因此假设您的id_product字段指向products表中的id字段:

SELECT fav.*, prod.* FROM favourites fav RIGHT JOIN products prod ON prod.id = fav.id
请注意,我在这里使用RIGHT JOIN是因为您希望确保右侧表(在本例中,Favorites具有要检索的信息),否则,如果id_产品指向不存在的id,您将得到空结果。还请注意,我分别为每个表指定了别名fav和prod,因为这使查询更容易/更快地编写


希望这有帮助

您可以使用内部联接

如果你遵循下面的例子,你就可以得到这个想法。我不知道你们的产品表上有什么。从您的描述来看,您可能会在用户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

您可以共享表格布局吗?子查询或联接。子查询示例:SELECT*FROM products WHERE id INSELECT id_product FROM FAVORITES WHERE id_user=3这可能是解决方案,但我希望获得产品信息,因此,这将是这样的,不是吗?从产品b中选择b.*在a.id_product=b.idies上加入收藏夹a这是您的查询应该是什么样子…这样您将根据产品id获得每个收藏夹产品。完成