如何在MySQL中执行此查询?

时间:2016-12-17 18:41:49

标签: mysql sql

我的摇滚墙MySQL数据库如下:

Harnesses (harnessID, manufacturer, condition)
Shoes (shoeID, size, condition)
Holds (holdID, holdType, manufacturer, condition)
Bolts (boltID, length, condition)

我如何查询条件为某些“价值”的所有商品? (例如'Good'/'Bad'/'Great')

理想情况下,结果会有架构:

ResultTable (itemType, itemID, condition)
[Where itemType = {Harness, Shoe, Hold, Bolt}]

解决

解决方案:将itemType字段添加到所有表并联合不同的选择(条件表为FK 1-Great,2-Good,3-Bad)

select itemType as Item, harnessID as ID, description as 'Condition' from harnesses join conditions where `condition` = conditions.conditionID and `condition` = 1

UNION 

select itemType as Item, shoeID as ID, description as 'Condition' from shoes join conditions where `condition` = conditions.conditionID and `condition` = 1

UNION

select itemType as Item, holdID as ID, description as 'Condition' from holds join conditions where `condition` = conditions.conditionID and `condition` = 1

UNION

select itemType as Item, boltID as ID, description as 'Condition' from bolts join conditions where `condition` = conditions.conditionID and `condition` = 1;

2 个答案:

答案 0 :(得分:0)

您需要使用IN运算符并提供多个值:

SELECT * FROM `ResultTable` WHERE `itemType` IN ('Harness', 'Shoe', 'Hold', 'Bolt')

答案 1 :(得分:0)

您可以使用Union来组合多个表Mysql Union。 但是Union有约束条件列数应该与数据类型相同。 因此,如果您的列号与查询相同,则

select Harness as ItemType, harnessID as ItemId where condition ='Good'
Union
select Shoes as ItemType, shoeID as ItemId where condition ='Good'
union
select Holds as ItemType, holdID as ItemId where condition ='Good'
union
select Bolts as ItemType, boltID as ItemId where condition ='Good'