所以我一直在努力让mySQL查询适用于我拥有的大型数据库。我有(假设)两个表Table_One和Table_Two。 Table_One有三列Type,Anima和TestID,Table_Two有两列Test_Name和Test_ID。值的示例如下:
TABLE_ONE
Type Animal TestID
-----------------------------------------
Mammal Goat 1
Fish Cod 1
Bird Chicken 1
Reptile Snake 1
Bird Crow 2
Mammal Cow 2
Bird Ostrich 3
Table_Two
Test_name TestID
-------------------------
Test_1 1
Test_1 1
Test_1 1
Test_1 1
Test_2 2
Test_2 2
Test_3 3
在Table_One中,所有类型都在一列之下,所有类型(哺乳动物,鱼类,鸟类,爬行动物)的值都在另一列(动物)之下。 Table_One和Two可以通过Test_ID
链接我正在尝试创建一个如下所示的表:
Test_Name Bird Reptile Mammal Fish
-----------------------------------------------------------------
Test_1 Chicken Snake Goat Cod
Test_2 Crow Cow
Test_3 Ostrich
这应该是我的决赛桌。我目前使用的方法是创建Table_One的多个实例并使用连接来形成此最终表。所以专栏Bird,Reptile,Mammal和Fish都来自Table_one的不同副本。
例如
Select
Test_Name As 'Test Case Name',
Table_Bird.Animal AS 'Birds',
Table_Mammal.Animal AS 'Mammal',
Table_Reptile.Animal AS 'Reptile,
Table_Fish.Animal AS 'Fish'
From Table_One
INNER JOIN TABLE_Two AS Table_Bird
On Table_One.TestID = Table_Bird.TestID
INNER JOIN TABLE_Two AS Table_Mammal
On Table_One.TestID = Table_Mammal.TestID
INNER JOIN TABLE_Two AS Table_Reptile
On Table_One.TestID = Table_Reptile.TestID
INNER JOIN TABLE_Two AS Table_Fish
On Table_One.TestID = Table_Fish.TestID
Where Table_Bird.Type LIKE 'Birds'
AND Table_Mammal.Type LIKE 'Mammals'
AND Table_Reptile.Type LIKE 'Reptiles'
AND Table_Fish.Type LIKE 'Fish'
此查询的问题是它仅适用于Birds,Mammals,Reptiles和Fish的所有条目都有一定价值的情况。如果一个字段为Test_Two或Test_Three为空,则它不会返回该记录。我在WHERE子句中使用Or代替And,但是它也没有用。
如果有人能指出我正确的方向,我真的很感激。
答案 0 :(得分:2)
尝试将INNER JOIN
语句替换为LEFT JOIN
。
答案 1 :(得分:1)
您可以尝试将您移动到JOIN条件并将其设为LEFT JOIN而不是INNER JOIN - 就像这样:
Select
Test_Name As 'Test Case Name',
Table_Bird.Animal AS 'Birds',
Table_Mammal.Animal AS 'Mammal',
Table_Reptile.Animal AS 'Reptile,
Table_Fish.Animal AS 'Fish'
From Table_One
LEFT JOIN TABLE_Two AS Table_Bird ON Table_One.TestID = Table_Bird.TestID AND Table_Bird.Type LIKE 'Birds'
LEFT JOIN TABLE_Two AS Table_Mammal ON Table_One.TestID = Table_Mammal.TestID AND Table_Mammal.Type LIKE 'Mammals'
LEFT JOIN TABLE_Two AS Table_Reptile ON Table_One.TestID = Table_Reptile.TestID AND Table_Reptile.Type LIKE 'Reptiles'
LEFT JOIN TABLE_Two AS Table_Fish ON Table_One.TestID = Table_Fish.TestID AND Table_Fish.Type LIKE 'Fish'