我有一个包含三个表的MySQL数据库:sample
,method
,compound
。
sample
包含以下列:id(PK)(int)
,date(date)
,compound_id(int)
,location(varchar)
,method(int)
,value(float)
method
包含以下列:id(PK)(int)
,label(varchar)
compound
有:id(PK)(int)
,name(varchar)
,unit(varchar)
我正在尝试生成一个SQL命令,该命令仅为以下条件提取唯一行:
sample.date
)compound.name
)sample.location
)sample.method
)但是,我想在标签中替换某些sample
列而不是数字:
sample.compound_id
与compound.id
匹配,后者具有相应的compound.name
和compound.unit
我试图查询的第一个SQL命令是:
SELECT sample.id, sample.date, compound.name, sample.location, method.label, sample.value, compound.unit
FROM sample, compound, method
WHERE sample.date = "2011-11-03"
AND compound.name = "Zinc (Dissolved)"
AND sample.location = "13.0"
AND method.id = 1;
以上命令的输出:
id date name location label value unit
1 2011-11-03 Zinc (Dissolved) 13.0 (1) Indivi... 378.261 μg/L
5 2011-11-03 Zinc (Dissolved) 13.0 (1) Indivi... 197.917 μg/L
9 2011-11-03 Zinc (Dissolved) 13.0 (1) Indivi... 92.4051 μg/L
但是,当我查看sample
并将sample.id
与返回的内容进行比较时:
id date compound_id location method value
1 2011-11-03 13 13.0 1 378.261
5 2011-11-03 14 13.0 1 197.917
9 2011-11-03 47 13.0 1 92.4051
compound.id
47对应compound.id
47和compound.name
“锌(溶解)”。化合物ID#13和#14分别是“铜(溶解)”和“铜(总)”。
因此,似乎返回符合sample.date
和sample.location
标准的行,而不考虑compound.name
。鉴于上述标准,我知道我的数据库应该只返回一行,而是我得到的一些sample.id
行与我指定的匹配sample.compound_id
完全不同compound.name
。
我想在第一行中以SELECT
编辑的列结束,以与我编写它们相同的顺序结束。这段代码适用于我在Python / Tkinter编写的一个小型数据库查看器/报告程序,并且依赖于统一的列。我用来初始化程序数据的代码按预期工作:
SELECT sample.id, sample.date, compound.name, sample.location, method.label, sample.value, compound.unit
FROM sample, compound, method
WHERE sample.compound_id = compound.id
AND sample.method = method.id;
其中sample
中的每个唯一行都包含sample.compound_id
到compound.name
和sample.method
到method.label
的替换,并在compound.unit
中添加最后。
问题#1:我如何重新构建查询以便它只返回符合该特定条件的行?
问题2:最终我需要一次指定多个sample.locations
。这就像为我需要的每个位置添加OR
语句一样简单吗?
答案 0 :(得分:2)
SELECT sample.id, sample.date, compound.name, sample.location, method.label, sample.value, compound.unit
FROM sample
INNER JOIN compound ON compound.id = sample.compound_id
INNER JOIN method ON method.id = sample.method
WHERE sample.date = '2011-11-03'
AND compound.name = 'Zinc (Dissolved)'
AND sample.location = "13.0"
AND method.id = 1;
答案 1 :(得分:1)
现在我想出了第一个问题,我想出了第二个问题:
SELECT sample.id, sample.date, compound.name, sample.location, method.label, sample.value, compound.unit
FROM sample
INNER JOIN compound ON compound.id = sample.compound_id
INNER JOIN method ON method.id = sample.method
WHERE sample.date = '2011-11-03'
AND compound.name = 'Zinc (Dissolved)'
AND sample.location IN ("13.0", "22.0")
AND method.id = 1;
只需在括号内为每个其他位置添加OR
。