我有3张桌子,下面给出了结构
+-------+-------------+------------+-----------------------------------+
| id(PK) | incident_display_id | account_id | customized_fields_id |
+-------+-------------+------------+-----------------------------------+
| 47614 | 33 | 394 | 1285,1286,1287,1288 |
+-------+-------------+------------+-----------------------------------+
+------+------------+----------+-------------+--------------------+
| id | account_id | field_id(FK) | incident_id(FK) | value |
+------+------------+----------+-------------+--------------------+
| 1285 | 394 | 49 | 47614 | Nikon 5MP |
| 1286 | 394 | 50 | 47614 | CDMA |
| 1287 | 394 | 51 | 47614 | Yes |
| 1288 | 394 | 84 | 47614 | 9317001007 |
+------+------------+----------+-------------+--------------------+
+----+------------+------------+---------------------+------+-------------+
| id | account_id | field_type | label | name | field_lable |
+----+------------+------------+---------------------+------+-------------+
| 49 | 394 | text_field | Camera | | |
| 50 | 394 | checkbox | Cellphone | | CDMA, GSM |
| 51 | 394 | radio | Sunglasses | | Yes, No |
| 52 | 394 | textarea | Credit Card | | 5 |
| 83 | 394 | radio | Cowboy Hat | | Yes,No |
| 84 | 394 | text_field | Emergency Contact # | | |
+----+------------+------------+---------------------+------+-------------+
现在我想只选择那些标签和table_incident
中存在的标签价值,
我解雇了以下查询
SELECT ti.id IncID,tcf.id labelID,tcfd.id dataID,tcf.label, tcfd.value
FROM table_customized_fields_data tcfd
INNER JOIN table_incident ti ON (ti.id = tcfd.incident_id)
INNER JOIN table_customized_fields tcf ON (tcf.id = tcfd.field_id)
WHERE tcfd.id IN (ti.customized_fields_id)
AND ti.id=47614
+-------+---------+--------+--------+-----------+
| IncID | labelID | dataID | label | value |
+-------+---------+--------+--------+-----------+
| 47614 | 49 | 1285 | Camera | Nikon 5MP |
+-------+---------+--------+--------+-----------+
但只返回一行,请大家告诉我,虽然每个子查询单独完成,但我在做什么错误。
注意:虽然此查询会重新生成所需的数据:
SELECT tcf.id AS labelID,tcf.label,tcfd.id AS dataID, tcfd.value
FROM table_customized_fields_data tcfd
JOIN table_customized_fields tcf ON tcf.id=tcfd.field_id
JOIN table_incident ti ON ti.id=tcfd.incident_id
WHERE ti.id=47614
但我认为必须有一些优化方式,请分享您的想法。
由于
答案 0 :(得分:1)
您的第二个查询是优化的方式。只需确保您在table_customized_fields_data.incident_id
上有索引。
此外,我认为您误解了IN的工作原理,引用手册:
expr IN(值,...)
如果expr等于IN列表中的任何值,则返回1,否则返回0 ...
所以你的
tcfd.id IN (ti.customized_fields_id)
相当于:
tcfd.id = ti.customized_fields_id
答案 1 :(得分:1)
ti.customized_fields_id
是一个字符串,而不是一个数组。它不匹配,但你得到一行,因为它是一个左连接,它是mysql。
你想要的是这样的:
SELECT ti.id IncID,tcf.id labelID,tcfd.id dataID,tcf.label, tcfd.value
FROM table_customized_fields_data tcfd
INNER JOIN table_incident ti ON ti.id = tcfd.incident_id
AND concat(',', customized_fields_id, ',') like concat('%,', tcfd.id, ',%')
INNER JOIN table_customized_fields tcf ON tcf.id = tcfd.field_id
WHERE ti.id=47614
,当用逗号分隔时,tcfd.id
在字符串customized_fields_id
中