根据另一个表上的查询获取表的行

时间:2014-05-06 09:14:13

标签: mysql cross-apply

我有这两个表

[Products]
ID
CompanyID,
Name,
PartNo,
IDSGroup,
ChartNo

[Company]
ID,
Name,
RegistrationNo,
RegistrationDate

我想在用户搜索公司名称时显示表中的这些列:

Company.Name, Product.Name, Product.PartNo, Product.IDSGroup

此搜索查询让我获得CompanyID

Select Company.ID from Company WHERE Company.Name LIKE "$userSearch%" 

现在我想使用Company.ID来获取此查询以获取所有产品

Select * from Products WHERE CompanyID = "id from previous query"

1 个答案:

答案 0 :(得分:2)

如果它在同一个数据库中,你可以加入两个表

SELECT
Company.Name, Products.Name, Products.PartNo, Products.IDSGroup
FROM
Company
LEFT JOIN Products
ON Company.ID = Products.CompanyID
WHERE
Company.Name LIKE "$userSearch%"