我有一个关于我现在正在处理的查询的问题:
我在数据库中有这5个表:Items
,ModelItems
,Category
,Brand
,Codes
项目:
ModelItems :
类别:
品牌:
代码:
我从Items表中选择每个产品,它在ModelItems中有一个模型,并且它被分配了Category.Name和Brand.Name,我可以处理所有这些,我的问题是使用Codes表。在代码中,有多个EAN和PN值分配给一个Items_id,我真的不知道如何访问它。
现在我已经想到了这个:
SELECT Items.*, Category.name as category, Brand.name as brand,
FROM Items
JOIN ModelItems ON ModelItems.id = Items.ModelItems_id
JOIN Category ON Category.id = ModelItems.Category_id
JOIN Brand ON Brand.id = ModelItems.Brand_id
WHERE Brand.name = ?
哪个不处理代码问题。我试图搜索这样的东西,但却找不到任何东西。我想从这个查询的输出是这样的:
id, Name, ModelItems_id, category, brand, [EAN, EAN, EAN], [PN, PN, PN]
我希望我的解释很清楚:-)
答案 0 :(得分:2)
SELECT
it.id,
it.`name`,
md.`id`,
cat.`name`,
br.`name`,
GROUP_CONCAT(co.`ean`),
GROUP_CONCAT(co.`pn`)
FROM
items it
INNER JOIN modelitems md
ON md.`id` = it.`modelitems_id`
INNER JOIN category cat
ON cat.`id` = md.`category_id`
INNER JOIN brand br
ON br.`id` = md.`brand_id`
INNER JOIN codes co
ON it.`id` = co.`items_id`
WHERE br.`name` = '?'
GROUP BY it.`id`
答案 1 :(得分:0)
那怎么样?
SELECT Items.*, Category.name AS category, Brand.name AS brand,
(SELECT group_concat(EAN SEPARATOR ', ') FROM Codes WHERE Codes.Items_id = Items.id GROUP BY Codes.Items_id) AS ean_list,
(SELECT group_concat(PN SEPARATOR ', ') FROM Codes WHERE Codes.Items_id = Items.id GROUP BY Codes.Items_id) AS pn_list
FROM Items
JOIN ModelItems ON ModelItems.id = Items.ModelItems_id
JOIN Category ON Category.id = ModelItems.Category_id
JOIN Brand ON Brand.id = ModelItems.Brand_id
WHERE Brand.name = ?