MySQL 加入 - 查询
MySQL Join - Query
我对如何构建查询有疑问。
我有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.
I am using InnoDB.
我希望用户能够输入 1-5 个选项,每个选项 1 个单词,它会交叉引用描述并告诉我同时拥有这两个选项的商店。
例如,选择 1 = 时钟,选择 2 = 纸,选择 3 = 食物。它会查询一个结果,该结果会给我商店和物品,这些物品的物品都与它们的描述相匹配。例如,它会 return Wal - Mart 基于此查询,因为它是唯一一家拥有与每个描述相匹配的商品的商店。非常感谢任何帮助。
根据您的描述,您可以这样做:
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;
已更新 fiddle 此处: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
fiddle: http://sqlfiddle.com/#!9/54708/5
我对如何构建查询有疑问。
我有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.
I am using InnoDB.
我希望用户能够输入 1-5 个选项,每个选项 1 个单词,它会交叉引用描述并告诉我同时拥有这两个选项的商店。
例如,选择 1 = 时钟,选择 2 = 纸,选择 3 = 食物。它会查询一个结果,该结果会给我商店和物品,这些物品的物品都与它们的描述相匹配。例如,它会 return Wal - Mart 基于此查询,因为它是唯一一家拥有与每个描述相匹配的商品的商店。非常感谢任何帮助。
根据您的描述,您可以这样做:
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;
已更新 fiddle 此处: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
fiddle: http://sqlfiddle.com/#!9/54708/5