多个表中的条件查询

时间:2011-02-11 07:36:47

标签: mysql join performance conditional

问候并感谢您查看我的问题,希望您能提供一些见解或指导。

我有三个表(基本上):'value_meta','value'和'values_visibility'。架构如下:

TABLE 'value_meta'

COMMENT: contains a list of different values, each referencing a different 'value' table

int id PK

tinyint value1 FK to value1.value

tinyint value2 FK to value2.value

tinyint value3 FK to value3.value

...



TABLE 'value'

COMMENT:  there are different value tables (for example, if it were for user profile data, there would be a value table for "occupation", "body type", and/or "education level"

tinyint id PK

varchar(255) value



TABLE 'value_visibility'

COMMENT:  one value visibility entry per value[n] in the 'value_meta' table, each a boolean value.  If 1, the coding query will return the value as rerefenced in 'value[n]' table.  if 0, return null
int id PK

BOOLEAN 'value1_visibility'

BOOLEAN 'value2_visibility'

BOOLEAN 'value3_visibility'

....

我想要做的是创建一个正确的MySQL查询来检查'value_meta'中的'每个'值',如果'value_visibility'中的相应值条目是1,则显示值varchar。否则返回null“。通过适当的我想使它最有效(dereived表与相关的子查询,适当的条件和功能使用......我听说ISNULL是坏的)。

我曾经擅长在大学期间直接建立查询,但经过多年没有使用它,我已经变成了三根稻草,没有一把完整的扫帚。谁能帮我?谢谢!

1 个答案:

答案 0 :(得分:0)

SELECT vm.id,
    IF(vv.id IS NULL, NULL, vm1v.value) value1,
    IF(vv.id IS NULL, NULL, vm2v.value) value2,
    IF(vv.id IS NULL, NULL, vm3v.value) value3
FROM value_meta vm 
    LEFT JOIN value vmv1 ON vm.value1 = vmv1.id
    LEFT JOIN value vmv2 ON vm.value1 = vmv2.id
    LEFT JOIN value vmv3 ON vm.value1 = vmv3.id
    LEFT JOIN value_visibility vv ON vm.id = vv.id AND vv.value1_visibility = 1

您应该考虑重构value_meta表,是否有理由将value1 2和3存储在同一行?