gpt4 book ai didi

MySQL 加入说明

转载 作者:行者123 更新时间:2023-11-29 00:14:44 25 4
gpt4 key购买 nike

我是 MySQL 和 PHP 的新手,我有面向对象的背景,试图围绕 SQL 查询进行思考有点令人沮丧。现在,我正尝试在给定用户 ID 和类别的同一个表中查找所有匹配的 ID。

这是我要回答的问题:给定用户 A 和类别 X,还有哪些其他用户与用户 A 对类别 X 有相同的兴趣,这些兴趣是什么?

这是我目前的代码:

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 个,与用户 C 共享 1 个,我只想查看包含共享兴趣的行(因此总共有 6 行,3用户 A,B 2 个,C 1 个)。

像这样创建临时表是最佳做法还是有更好的方法?我宁愿不创建临时表,但我无法让子选择查询工作子选择返回超过 1 行。非常感谢任何和所有建议,谢谢!

最佳答案

我认为您不需要使用临时表。您可以使用单个 select 语句。下面的查询获取指定类别的所有 interest_map 和兴趣记录,并使用 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;

关于MySQL 加入说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23407935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com