【发布时间】:2013-01-24 17:09:35
【问题描述】:
我有一个 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 分别是“Copper (Dissolved)”和“Copper (Total)”。
所以它似乎返回满足sample.date 和sample.location 条件的行,而不考虑compound.name。鉴于上述标准,我知道我的数据库应该只返回一行,但我得到的一些 sample.id 行与我指定的匹配 compound.name 具有完全不同的 sample.compound_id。
我想以第一行中SELECTed 的列结束,以与我编写它们的顺序相同。此代码适用于我在 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 语句一样简单?
【问题讨论】:
-
对于第一个查询 - 不符合条件的查询 - 缺少加入像 sample.comapund_d = Compound.id 这样的信息。此外,您可能需要检查 Compound.name 值的拼写或考虑使用 Compound.name LIKE 'Zinc%'
-
Anda Iancu:我是一个 SQL 假人。我不确定 INNNER JOIN 语法如何处理这么多的条件。