2014-03-06 35 views
1

我是MySQL和PHP的新手,我来自OO背景,试图围绕SQL查询来包装头,这有点令人沮丧。现在我试图在给定用户ID和类别的同一表中找到所有匹配的ID。MySQL加入澄清

下面是我试图回答的问题:给定用户A和类别X,还有哪些其他用户在类别X中与用户A具有相同的兴趣以及这些兴趣是什么?

下面的代码我到目前为止:

CREATE TEMPORARY TABLE IF NOT EXISTS t_int_map AS (
SELECT intmap.fb_id, intmap.interest_id 
FROM interest_map AS intmap 
INNER JOIN interests AS i ON intmap.interest_id = i.id 
WHERE intmap.fb_id = <ID of User A> AND i.category = '<Category User A selects'); 

SELECT im.fb_id, im.interest_id, i.name 
FROM interest_map AS im 
INNER JOIN interests AS i ON im.interest_id = i.id 
INNER JOIN t_int_map AS t_ 
WHERE t_.interest_id = im.interest_id 

这是给我所有利益用户A的结果集具有在X类以及谁拥有匹配其他用户该类别下的利益。我想放弃所有不与其他用户共享的兴趣。 IE:如果用户A在X类下有10个利益,并与用户B共享2个利益,我想只看到包含共享兴趣的行(所以总共有6行,3对于用户A,对于B为2,对于C为1)。

最好的做法是创建一个像这样的临时表,还是有更好的方法来做到这一点?我宁愿不创建一个临时表,但我无法获得一个子选择查询来工作,该子选择返回多于一行。任何和所有的建议非常感谢,谢谢!

回答

1

我不认为你需要使用临时表。您可以使用单个选择语句。下面的查询获取指定类别的所有interest_map和interest记录,并使用EXISTS将结果限制为指定用户的兴趣。

请参见:http://dev.mysql.com/doc/refman/5.6/en/exists-and-not-exists-subqueries.html

DROP TABLE IF EXISTS interest_map; 

DROP TABLE IF EXISTS interests; 



CREATE TABLE interests 
(
    interest_id INT NOT NULL PRIMARY KEY 
    , category VARCHAR(25) NOT NULL 
    , description VARCHAR(50) NOT NULL 
); 

CREATE TABLE interest_map 
(
    fb_id VARCHAR(10) NOT NULL 
    , interest_id INT NOT NULL 
    , CONSTRAINT FOREIGN KEY (interest_id) REFERENCES interests (interest_id) 
    , CONSTRAINT PRIMARY KEY (fb_id , interest_id) 
); 


INSERT INTO interests (interest_id, category, description) 
VALUES 
    (1, 'Programming', 'Java') 
    ,(2, 'Programming', 'PHP') 
    ,(3, 'Programming', 'C#') 
    ,(4, 'Database', 'Oracle') 
    ,(5, 'Database', 'MySQL') 
    ,(6, 'Database', 'DB2') 
    ,(7, 'Operating System', 'Linux') 
    ,(8, 'Operating System', 'Windows'); 


INSERT INTO interest_map (fb_id , interest_id) 
VALUES 
    ('User A', 1) 
    ,('User A', 3) 
    ,('User B', 1) 
    ,('User B', 5) 
    ,('User B', 2) 
    ,('User B', 7) 
    ,('User C', 1) 
    ,('User C', 3) 
    ,('User C', 4) 
    ,('User C', 7); 


SET @user = 'User A'; 
SET @category = 'Programming'; 

SELECT 
    m.fb_id 
    , i.interest_id 
    , i.description 
FROM interests AS i 
    INNER JOIN interest_map AS m 
     ON (i.interest_id = m.interest_id) 
WHERE i.category = @category -- get interests in this category 
    AND EXISTS (
      SELECT * 
      FROM interest_map AS m2 
      WHERE m2.fb_id = @user 
       AND m2.interest_id = m.interest_id 
     ) -- the exists clause limits results to interests of the specified user 
ORDER BY m.fb_id, i.description; 
+0

谢谢!我正在研究使用变量作为另一个潜在的解决方案,我在临时中只有临时表解决方案。现在我只需要修改它并转换成PHP。 –