[英]MYSQL select results from 3 tables with an array of ids
Ok, so I have 3 mysql tables where I need to extract data from. 好的,所以我有3个mysql表,我需要从中提取数据。 Anything to do with joins really gets me stuck! 与联接有关的一切真的让我陷于困境!
Table 1 = products (productid, name) 表1 =产品(产品ID,名称)
Table 2 = category (categoryid, name) 表2 =类别(类别,名称)
Table 3 = categoryproduct (categoryid, productid) - my join table 表3 = categoryproduct(categoryid,productid)-我的联接表
I have an array of product ids which I need to get a random selection of products that fall into the same categories as these products. 我有一个产品ID数组,我需要从中随机选择与这些产品属于同一类别的产品。
The idea is that the results of the query will display a section in my cart of similar/related products that the customer may like 这个想法是查询的结果将在我的购物车中显示客户可能喜欢的类似/相关产品的一部分
So something like 所以像
SELECT name etc FROM table1
WHERE table2.categoryid of results of the query = table3.categoryid of current products
ORDER BY RAND()
LIMIT 3
How do I write that?? 我该怎么写?
Assuming you're using PHP, following method will fetch 10 related products from database. 假设您使用的是PHP,以下方法将从数据库中获取10种相关产品。
$productids = array(1002,789,999,203,321);
$sql = '
SELECT * FROM
products p JOIN categoryproduct pc
ON p.productid = pc.productid
WHERE pc.categoryid IN(
SELECT DISTINCT(categoryid) FROM
products inner_p JOIN categoryproduct inner_pc
ON inner_p.productid = inner_pc.productid
WHERE inner_p.productid IN('.implode(',',$productids).')
)
ORDER BY RAND()
LIMIT 10';
If i have understood your problem correctly then this query may help. 如果我正确理解了您的问题,那么此查询可能会有所帮助。 Here instead of subquery you can give comma separated string which contains categoryid of different products selected by the user. 在这里,您可以给以逗号分隔的字符串(而不是子查询),该字符串包含用户选择的不同产品的categoryid。
select p.name
from products p,categoryproduct cp
where p.productid=cp.productid
and cp.categorid in(
select categoryid
from cartitems)
order by RAND()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.