开发者

Conditional Queries Among Multiple Tables

Greetings and thank you for looking at my question, I hope you can provide some insight or direction.

I have three tables (fundamentally): 'value_meta', 'value', and 'values_visibility'. The schema follows:

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'

BOO开发者_如何学编程LEAN 'value2_visibility'

BOOLEAN 'value3_visibility'

....

What I want to do is create a proper MySQL query to check "for each 'value' in 'value_meta', if corresponding value entry in 'value_visibility' is 1, display value varchar. else return null". By proper I want to make it most efficient (dereived tables vs. correlated subqueries, proper conditionals and function uses... I hear ISNULL is bad).

I used to be good at query building straight out of my mind back in college but after years of not using it, I've become three straws short of a full broom. Can anyone help me? Thanks!


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

You should think about restructuring your value_meta table, is there a reason why you are storing value1 2 and 3 in the same row?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜