我不知道标题是否有用,但我正在试图找出一个MySQL数据库的SELECT语句,它给了我匹配的项目。我有两张桌子。
示例:
Offers
------
FK_User_ID | FK_Skill_ID | (other columns that are not relevant)
1 1
2 2
Requests
--------
FK_User_iD | FK_Skill_ID | (other columns that are not relevant)
1 | 2
2 | 1
你明白我的意思吗?用户1具有技能1并且寻求技能2 - 用户2具有技能2并且寻求技能1.我们有匹配!
说我是用户1.如何获得与我/我相匹配的用户和技能?
作为用户1,我想检索以下数据:
FK_User_ID | FK_Skill_ID | Type
2 1 Request
2 2 Offer
我希望我的问题很明确。非常感谢任何帮助。
更多详细信息:用户可以拥有多项技能,并且可以请求多项技能。匹配并不意味着每个技能都需要匹配,但至少有一个。我想知道哪个然后。这只是与匹配的技能有关。
答案 0 :(得分:3)
SELECT FK_User_ID, FK_Skill_ID, 'Offer' AS Type FROM offers WHERE FK_Skill_ID IN (SELECT FK_Skill_ID FROM requests WHERE FK_User_ID = 1)
UNION
SELECT FK_User_ID, FK_Skill_ID, 'Request' AS Type FROM requests WHERE FK_Skill_ID IN (SELECT FK_Skill_ID FROM offers WHERE FK_User_ID = 1)
此查询将返回ID为1的用户的请求/要约列表。它将返回用户1请求的所有要约以及用户1提供的所有要求。如果您可以更新有关数据的更多详细信息,正如@Chris建议的那样,我可能会提供更多帮助。
更新:
如果你需要匹配请求和提供,那么它将会更多一些工作。
SELECT matching_offers.*, 'Offer' as type FROM
(SELECT FK_User_ID, FK_Skill_ID FROM offers WHERE FK_Skill_ID IN (SELECT FK_Skill_ID FROM requests WHERE FK_User_ID = 1)) AS matching_offers INNER JOIN
(SELECT FK_User_ID, FK_Skill_ID FROM requests WHERE FK_Skill_ID IN (SELECT FK_Skill_ID FROM offers WHERE FK_User_ID = 1)) matching_requests ON matching_offers.FK_User_ID=matching_requests.FK_User_ID
UNION
SELECT matching_requests.*, 'Request' as type FROM
(SELECT FK_User_ID, FK_Skill_ID FROM offers WHERE FK_Skill_ID IN (SELECT FK_Skill_ID FROM requests WHERE FK_User_ID = 1)) AS matching_offers INNER JOIN
(SELECT FK_User_ID, FK_Skill_ID FROM requests WHERE FK_Skill_ID IN (SELECT FK_Skill_ID FROM offers WHERE FK_User_ID = 1)) matching_requests ON matching_offers.FK_User_ID=matching_requests.FK_User_ID
这将非常低效但应该有效。也许有人认为SQLfu比我的好,可以改善它。)
答案 1 :(得分:0)
从这样的查询开始,它返回技能匹配的两个表中每个可能的行组合:
SELECT offers.FK_User_ID as offering, offers.FK_Skill_ID as skill, requests.FK_User_ID as requesting
FROM offers, requests
WHERE offers.FK_Skill_ID = requests.FK_Skill_ID
要查找符合“您的”优惠的用户和技能,请选择offering
是'您'的地方。要查找符合“您的”请求的用户和技能,请选择requesting
是'您'的位置。