简体   繁体   中英

SQL to select brand from a table, if another table has a product with that brand

Using MySQL and PHP.

I have two tables products and stock.

products has { productID | product | brand|}

stock has { ID | storeID | productID | qty | price }

I need to get all of the brands available at a specific store.

So here is what I have that doesn't work.

SELECT DISTINCT brand 
  FROM products 
 WHERE 'products.productID' = 'stock.productID' 
   AND 'stock.storeID' = 1

If I remove the compare "WHERE" it returns all of the brands.

Try

Select p.brand FROM products p, stock s 
WHERE p.productID=s.productID and s.storeID='1'
SELECT DISTINCT p.brand 
FROM products p inner join stock s on p.productID=s.productID
WHERE `stock.storeID` = 1

mark the diff between ` and '

try

 "SELECT p.* FROM Products p 
 INNER JOIN stock s USING(productID)
 WHERE s.storeID = '".(int)$givenID."' 
 GROUP BY p.brand";

我们也可以这样写

SELECT DISTINCT p.brand FROM products p , stock s where  p.productID=s.productID(+) and stock.storeID = 1

Try this:

SELECT DISTINCT p.brand 
FROM   products p 
             INNER JOIN stock s 
                  ON p.productID=s.productID
WHERE s.`storeID` = 1

This will help

select p.brand 
  from product p, stock s 
 where p.productID = s.productID
   and s.storeID = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM