简体   繁体   English

mysql查询-仅从另一个表中选择id = id,而该表中的字段=值

[英]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: 它说$ colour_sql的部分我想要的东西说:

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. 如果要使用表格colour进行联接,则需要进行联接或子选择。

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. 但是我观察到您的颜色表中有product_id。 Why don't you do the reverse in the Items table you add the colour id. 为什么不在Items表中做相反的操作,添加颜色ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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