0

我有一个包含三个表的 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.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.id47 对应于compound.id47 和compound.name“锌(溶解)”。化合物 ID #13 和 #14 分别是“铜(溶解)”和“铜(总)”。

因此,它似乎返回满足sample.datesample.location不考虑compound.name. 鉴于上述标准,我知道我的数据库应该只返回一行,但我得到的一些行与我指定的匹配sample.id完全不同。sample.compound_idcompound.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_idtocompound.namesample.methodtomethod.label并在compound.unit最后添加。

问题 #1:我需要如何重组我的查询,以便它只返回满足特定条件的行?

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

4

2 回答 2

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;
于 2013-01-24T17:21:42.033 回答
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在括号内为其他位置添加 s 即可。

于 2013-01-24T17:30:24.543 回答