简体   繁体   中英

mysql query - only select where id = id from another table and a field in that table = a value

my title may not explain what I am looking for, this is my current query for pulling in products for a shop:

mysql_query("SELECT * FROM Items 
             WHERE ((Items.menu_id='$menu_id' AND Items.status='1') 
                   $colour_sql) 
             $order_sql 
             LIMIT $lim_from,$limit_per_page");

The part where it says $colour_sql I want to have somthing that says:

AND (Items.id=colour.product_id AND colour.colour='pink')

So it only show products that are pink, with the colours being in a seperate table. I have searched for answers, but I can't seem to find one explaining my situation, maybe its because I don't know exactly what i'm, looking for, any help is appreciated thanks.

If you want to join with table colour you need to do either a join or a subselect.

Join

$menu_id = mysql_real_escape_string($menu_id);
mysql_query = "SELECT i.* 
  FROM items i
  INNER JOIN colour c ON (c.product_id = i.id)
  WHERE i.menu_id = '$menu_id' 
    AND i.status = '1'
    AND c.colour = 'pink'
  ORDER BY .....
  LIMIT {intval($limit_per_page)} OFFSET {intval($lim_from)} ";

Subselect

$menu_id = mysql_real_escape_string($menu_id);
mysql_query = "SELECT i.* 
  FROM items i
  WHERE i.menu_id = '$menu_id' 
    AND i.status = '1'
    AND i.id IN (SELECT c.product_id FROM colour c WHERE c.colour = 'pink')
  ORDER BY .....
  LIMIT {intval($limit_per_page)} OFFSET {intval($lim_from)} ";

maybe an inner join?

[...]
FROM Items
INNER JOIN colour
ON colour.id = Items.colour_id
WHERE [blablabla]
AND colour.colour = 'pink'

You need to add the colour table to your query:

FROM Items,colour

or

From Items INNER JOIN colour ON Items.id = colour.product_id

But I observed that you have the product_id in your colour table. Why don't you do the reverse in the Items table you add the colour id.

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