我想创建一个可以在以后使用的联系人表。所以结构:
table contact: id, contact_type
table contact_meta : id, contact_id, meta_key, meta_value
这个查询是不好的做法? (超过10个加入?)
select c.id,
cm1.meta_value as name,
cm2.meta_value as email,
cm3.meta_value as bussiness_phone
from contact as c
left join contact_meta as cm1 on (cm1.contact_id = c.id)
left join contact_meta as cm2 on (cm2.contact_id = c.id)
left join contact_meta as cm3 on (cm3.contact_id = c.id)
where c.contact_type = 'supplier' and
cm1.meta_key = 'name' and
cm2.meta_key = 'email' and
cm3.meta_key = 'bussiness_phone' ORDER BY c.id DESC
答案 0 :(得分:0)
查询不是“不良做法”,而是将额外条件移到它们所属的连接子句中:
select c.id,
cm1.meta_value as name,
cm2.meta_value as email,
cm3.meta_value as bussiness_phone
from contact as c
left join contact_meta as cm1 on cm1.contact_id = c.id and cm1.meta_key = 'name'
left join contact_meta as cm2 on cm2.contact_id = c.id and cm2.meta_key = 'email'
left join contact_meta as cm3 on cm3.contact_id = c.id and cm3.meta_key = 'bussiness_phone'
order by c.id desc
请注意删除不必要的括号。