我有5张桌子:
现在,我想要一个类别产品的所有数据(让我们说所有来自ID为1的类别),但只有一个产品是针对特定网站的。
我的第一次尝试是
SELECT p.*
FROM `products` p,
`categories` c,
`x_product_site` xps,
`x_product_category` xpc
WHERE c.`id` = '%1\$s'
AND c.`id` = xpc.`category_id`
AND xpc.`product_id` = xps.`product_id`
AND p.`id` = xpc.`product_id`
ORDER BY p.`name` ASC
显然这不是这样做的方法。
有人可以给我一个有或没有连接的正确查询吗?
答案 0 :(得分:2)
试试这个:
如果您有 site_id ,请使用以下查询:
SELECT P.id, P.name
FROM products P
INNER JOIN x_products_categories PC ON P.id = PC.product_id AND PC.category_id = 1
INNER JOIN x_products_site PS ON P.id = PS.product_id
WHERE PS.site_id = 1
ORDER BY P.name;
如果您有 site_name ,请使用以下查询:
SELECT P.id, P.name
FROM products P
INNER JOIN x_products_categories PC ON P.id = PC.product_id AND PC.category_id = 1
INNER JOIN x_products_site PS ON P.id = PS.product_id
INNER JOIN sites S ON PS.site_id = S.id
WHERE S.site_name LIKE '%site_name%'
ORDER BY P.name;
答案 1 :(得分:1)
SELECT
p.*
FROM
products p
, categories c
, sites s
, x_product_categories xpc
, x_product_site xps
WHERE xpc.category_id = c.id
AND xpc.product_id = p.id
AND xps.product_id = p.id
AND xps.site_id = s.id
AND s.sitename = "site1"
AND c.id = 1 ;
答案 2 :(得分:0)
无需连接表格。毕竟,您只想从产品中进行选择。使用IN子句查看产品是否在其他表中。这里根本不需要表格类别。该表中没有任何内容可以为我们提供所需的任何信息。
假设您想要类别1和网站5的产品。
select *
from products
where product_id in (select pc.product_id from x_product_category pc where pc.id = 1)
and product_id in (select ps.product_id from x_product_site ps where ps.id = 5);
为了完整起见,您可以使用EXISTS执行相同的操作。 (好吧,毕竟,你想知道其他表中是否存在产品的记录。)
select *
from products p
where exists (select * from x_product_category pc where pc.product_id = p.id and pc.id = 1)
and exists (select * from x_product_site ps where ps.product_id = p.id and ps.id = 5);