我有一个包含三个表的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_id与具有相应compound.idcompound.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语句一样简单吗?

最佳答案

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;

关于mysql - 从具有多个条件的多个表中选择,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14506853/

10-11 02:08