是否可以优化我编写的此查询
我创建了一种动态虚拟数据库,使我的用户能够在不影响数据库结构的情况下添加自定义字段。到目前为止,这是一个非常简化的结构视图。
tables | columns
db_cases | caseid
db_structure | fieldname
db_data | fieldname, data, caseid
db_names | nameid
我正在尝试将案例输出到html表
希望其余部分是自我解释的,你可以看到它是多么低效。我可以通过连接做同样的事情吗?
SELECT
case_id,
(SELECT data_field_value
FROM db_data
WHERE data_case_id = case_id AND data_field_name = 'casestatus'
) AS casestatus,
(SELECT forename_company
FROM db_names
WHERE name_id = (SELECT data_field_value
FROM db_data
WHERE data_case_id = case_id AND data_field_name = 'client1'
)
) AS client1_forename_company
FROM db_cases
由于
答案 0 :(得分:2)
实际上,Chibuzo是对的。首先删除它:-))但之前,玩一点,这是一个很好的大脑运动,像国际象棋或其他东西: - )
select
case_id,
d_status.data_field_value as case_status,
d_client1_name.forename_company as client1_forename_company
from db_cases
join db_data as d_status
on d_status.data_case_id = case_id
AND d_status.data_field_name = 'casestatus'
join db_data as d_client1
on d_client1.data_case_id = case_id
AND d_client1.data_field_name = 'client1'
join db_names as d_client1_name
on d_client1_name.name_id = d_client1.data_field_value
我希望这些没有子查询的直接连接效率更高,但你必须对它进行测试 - 优化中经常会有惊喜。