mysql连接相同的表名和列名

时间:2011-10-29 17:34:25

标签: php mysql sql

我有一张表profile_data,结构如下:

id, user_id, field_id, value

对于任何匹配多个zipcodes且其国家/地区为美国的用户,我需要获取user_id。

到目前为止,我有这个不起作用的查询:

SELECT data1.user_id 
  FROM profile_data data1, profile_data data2 
 WHERE data1.field_id = 80
   AND ( value = '94114' OR value = '94146' OR value = '94117' )
   AND data2.field_id = 90
   AND value = 'United States'

3 个答案:

答案 0 :(得分:1)

试试这个

SELECT DISTINCT user_id 
FROM profile_data data1
WHERE field_id = 80 AND value IN ('94114', '94146', '94117')
    AND EXISTS   (SELECT * 
              FROM profile_data 
              WHERE field_id = 90 
                  AND value = 'United States' 
                  AND user_id = data1.user_id)

假设您有个人资料和个人资料数据表,您可以执行此操作并避免使用不同的排序:

SELECT user_id 
FROM profile
WHERE EXISTS (SELECT * 
              FROM profile_data 
              WHERE field_id = 80 
                  AND value IN ('94114','94146','94117') 
                  AND user_id = profile.user_id)
AND EXISTS   (SELECT * 
              FROM profile_data 
              WHERE field_id = 90 
                  AND value = 'United States' 
                  AND user_id = profile.user_id)

修改 我根据Kris的解决方案/改进删除了我的一个子查询。

答案 1 :(得分:1)

以下是我对你可能要做的事情的看法:

SELECT user_id
FROM profile_data
WHERE (field_id = 80 AND value IN ('94114', '94146', '94117'))
OR (field_id = 90 AND value = 'United States')

修改

对不起,我没有意识到每个用户可能有多行。如果是这种情况,则上述操作无效。上面答案中编辑的存在语句将是。虽然你不需要同时做两个子查询:

 SELECT user_id FROM profile_data p1
 WHERE (field_id = 80 AND value IN ('94114', '94146', '94117'))
 AND EXISTS (SELECT 1 FROM profile_data p2 WHERE field_id = 90 AND value = 'United States' AND p1.user_id = p2.user_id)

希望您的优化器无论如何都会将其减少到正确的连接数。

另外,邮政编码是针对特定国家/地区的。所以这个具体的例子是多余的,但是有很多有效的用例。

答案 2 :(得分:0)

试试这个:

SELECT us_users.user_id
FROM
    (
        SELECT user_id
        FROM profile_data
        WHERE field_id = 90 AND value = 'United States'
    ) AS us_users
    INNER JOIN (
        SELECT user_id
        FROM profile_data
        WHERE field_id = 80 AND value IN ('94114','94146','94117')
    ) AS zipcodes
        ON us_users.user_id = zipcodes.user_id