我有两个MySQL表
[client_data]和[default_values]
如下图所示:
Client_Data表
Default_Values
我的问题是:
我想通过加入default_values表c_value.string [split(1)]来查看client_data表。怎么做?
见下面的示例;
答案 0 :(得分:1)
您可以通过两次加入default_values
来完成此操作。我使用LEFT JOIN
,因此它包含default_values
中没有匹配数据的客户的结果(因为您在您的sqlfiddle中遗漏了Philipines)。
SELECT client_id, SUBSTRING_INDEX(v2.c_value, ',', -1) AS type, SUBSTRING_INDEX(v1.c_value, ',', -1) AS nationality
FROM client_data AS c
LEFT JOIN default_values AS v1 ON c.nationality = SUBSTRING_INDEX(v1.c_value, ',', 1) AND v1.category = 'Nationality'
LEFT JOIN default_values AS v2 ON c.type = SUBSTRING_INDEX(v2.c_value, ',', 1) AND v2.category = 'c_type'
答案 1 :(得分:0)
这应该工作......我在sql server上试过这个。请查看mysql
中的substring,charindex和len等效函数select
client_id,cvalue as type, nvalue as nationality
from
client_data,
(select
category,
substring(c_value,1, charindex(',',c_value)-1) as nindex,
substring(c_value,charindex(',',c_value)+1,len(c_value)) as nvalue
from
default_values
where category = 'Nationality') nTable,
(select
category,
substring(c_value,1, charindex(',',c_value)-1) as cindex,
substring(c_value,charindex(',',c_value)+1,len(c_value)) as cvalue
from
default_values
where category = 'c_type') cTable
Where client_data.type = cTable.cindex AND client_data.nationality = nTable.nindex