从具有多个条件的多个表中进行选择

时间:2013-01-24 17:09:36

标签: mysql sql

我有一个包含三个表的MySQL数据库:samplemethodcompound

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_idcompound.id匹配,后者具有相应的compound.namecompound.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.datesample.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_idcompound.namesample.methodmethod.label的替换,并在compound.unit中添加最后。

问题#1:我如何重新构建查询以便它只返回符合该特定条件的行?

问题2:最终我需要一次指定多个sample.locations。这就像为我需要的每个位置添加OR语句一样简单吗?

2 个答案:

答案 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