我对如何构建查询有疑问。
我有2张桌子。
Store
- store_id -- primary key
- zip_code
Merchandise
- item_id -- primary key
- item_name
- description
- cost
- storeID -- foreign key that references the store_id from the store.
我正在使用InnoDB。
我希望用户能够输入1-5个选项,每个1个单词,它会交叉引用解密并告诉我同时拥有它们的商店。
例如,选择1 =时钟,选择2 =纸张,选择3 =食物。它将查询一个结果,该结果将为我提供具有与其描述相匹配的项目的商店和商品。例如,它将基于此查询返回沃尔玛,因为它将是唯一一个具有匹配每个描述的项目的商店。非常感谢任何帮助。
答案 0 :(得分:0)
根据您的描述,您可以这样做:
select storeid
from merchandise
where description = 'clock' or description = 'paper' or description = 'food'
group by storeid
having count(*) = 3;
这里有一个示例:http://sqlfiddle.com/#!9/e6c2d/3
但是有更好的方法来组织您的架构。
修改强>
根据评论中的进一步要求更新:
此查询将为您检索商店详细信息,并通过zip_code检索:
select storeid, name
from merchandise m
inner join stores s
on m.storeid = s.store_id
where (description = 'clock' or description = 'paper' or description = 'food') and zip_code = 3456
group by storeid
having count(*) = 3;
此处更新了小提琴:http://sqlfiddle.com/#!9/c94dd/1
修改强>
修改为在使用like
select storeid, name
from merchandise m
inner join stores s
on m.storeid = s.store_id
where (description like '%clock%' or description like '%paper%' or description like '%food%')
group by storeid
having count(case when description like '%clock%' then 1 end) >= 1
and count(case when description like '%paper%' then 1 end) >= 1
and count(case when description like '%food%' then 1 end) >= 1