Mysql选择行值

时间:2013-12-03 05:48:53

标签: mysql sql

我试图为wordpress创建一个插件,我遇到一个像这样的结构的表

enter image description here

示例数据

enter image description here

如果我想获取

,我的MySQL Select查询应该如何
user_id  where City = 'CityName' and Gender = 'Male' //sample query

这样的东西
SELECT user_id,value,country FROM `wp_bp_xprofile_data` WHERE value = 'CityName' AND value = 'Male' GROUP BY user_id

OUTPUT应该

1 | nameofperson_1 | country_name
2 | nameofperson_2 | country_name
3 | nameofperson_3 | country_name
4 | nameofperson_4 | country_name

3 个答案:

答案 0 :(得分:1)

假设wp_bp_xprofile_data适用于上表,而value具有实际价值而非“名称”,“性别”等。

你能试试吗?

SELECT t1.user_id, t1.value, t2.value
FROM wp_bp_xprofile_data t1
  INNER JOIN wp_bp_xprofile_data t2 ON t1.user_id = t2.user_id
WHERE t1.field_id = 270 AND t1.value = 'Mail'
  AND t2.field_id = 354 AND t2.value = 'CityName'

答案 1 :(得分:1)

现在我看到您的问题有所需的输出,请尝试以下方法:

SELECT t3.user_id, t3.value, t.value FROM
wp_bp_xprofile_data t 
LEFT JOIN wp_bp_xprofile_data t1 ON t1.user_id = t.user_id
LEFT JOIN wp_bp_xprofile_data t2 on t2.user_id = t.user_id
LEFT JOIN wp_bp_xprofile_data t3 on t3.user_id = t.user_id
WHERE t2.field_id = 270 AND t2.value="Male" AND
t1.field_id=354 AND t1.value="CityName" AND
t3.field_id=1 AND
t.field_id=73

答案 2 :(得分:1)

为了使field_id与特定值匹配,您必须将它们成对匹配(field_id AND value)。然后你将不得不计算比赛的数量。

SELECT user_id FROM wp_bp_xprofile_data t
WHERE (field_id = 270 AND value = 'Gender') OR
      (field_id = 354 AND value = 'City')
GROUP BY user_id
HAVING COUNT(*) = 2

小提琴here

应用实体 - 属性 - 值(EAV)模型导致的一件事是您的表没有规范化,那么您应该确保给定的{{field_id没有user_id 1}}具有相同的值。

解决方法是查询:

HAVING COUNT(distinct field_id) = 2

但是,这当然不能解决数据问题。

修改

鉴于您的问题更新...为了返回附加数据,可能会将条件放在having子句中可能更好:

SELECT
  user_id,
  max(case when field_id = 270 then value end) nameOfPerson,
  max(case when field_id = 354 then value end) cityName
FROM wp_bp_xprofile_data t
GROUP BY user_id
HAVING SUM(
  (field_id = 270 AND value = 'Gender') +
  (field_id = 354 AND value = 'City')
) = 2

小提琴here