2010-06-05 54 views
1

我有3個表格:項目,技能和project_skills。在項目表中,我持有項目的一般數據。第二個表技能我擁有技能ID和技能名稱我也有project_skills表是持有項目的技能關係。下面是表的方案:如何創建這個複雜的查詢?

CREATE TABLE IF NOT EXISTS `project_skills` (
    `project_id` int(11) NOT NULL, 
    `skill_id` int(11) NOT NULL, 
    KEY `project_id` (`project_id`), 
    KEY `skill_id` (`skill_id`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci; 


CREATE TABLE IF NOT EXISTS `projects` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `employer_id` int(11) NOT NULL, 
    `project_title` varchar(100) COLLATE utf8_turkish_ci NOT NULL, 
    `project_description` text COLLATE utf8_turkish_ci NOT NULL, 
    `project_budget` int(11) NOT NULL, 
    `project_allowedtime` int(11) NOT NULL, 
    `project_deadline` datetime NOT NULL, 
    `total_bids` int(11) NOT NULL, 
    `average_bid` int(11) NOT NULL, 
    `created` datetime NOT NULL, 
    `active` tinyint(1) NOT NULL, 
    PRIMARY KEY (`id`), 
    KEY `created` (`created`), 
    KEY `employer_id` (`employer_id`), 
    KEY `active` (`active`), 
    FULLTEXT KEY `project_title` (`project_title`,`project_description`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci AUTO_INCREMENT=3 ; 

CREATE TABLE IF NOT EXISTS `skills` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `category` int(11) NOT NULL, 
    `name` varchar(100) COLLATE utf8_turkish_ci NOT NULL, 
    `seo_name` varchar(100) COLLATE utf8_turkish_ci NOT NULL, 
    `total_projects` int(11) NOT NULL, 
    PRIMARY KEY (`id`), 
    KEY `seo_name` (`seo_name`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci AUTO_INCREMENT=224 ; 

我要選擇具有相關技能的名字項目。我想我必須使用JOIN,但我不知道該怎麼辦。由於

+0

這是值得一讀一個SQL教程作爲複習。 http://www.w3schools.com/sql/sql_join.asp – 2010-06-05 14:45:56

+0

請舉例說明「相關技能名稱」。 – 2010-06-05 20:47:30

+0

技能ID - 項目ID關係在項目技能名稱中保留,但我想要在技能表中保存的技能名稱。我的意思是這些技能名稱通過說「相關技能名稱」 – mTuran 2010-06-06 22:46:03

回答

1

這聽起來像一個JOIN是完全正確的:

SELECT ... 
FROM projects 
INNER JOIN project_skills ON (project_skills.project_id = projects.id) 
INNER JOIN skills ON (skills.id = project_skills.skill_id) 
+0

這將只返回具有相關技能的項目,不相關的技能名稱 – 2010-06-05 20:44:40

+0

技能名稱存儲在skills.name列中;如果需要這些名稱,那麼可以簡單地將列添加到「SELECT」字段的列表中 – VoteyDisciple 2010-06-06 04:36:25

1
select * from projects 
left join project_skills on projects.id = project_skills.project_id 
left join skills on project_skills.skills_id = skills .id 

記:你並不需要所有列,但是這將讓你看到是怎麼回事,你選擇你所需要的列前。

+0

這將只返回與技能相關的項目,而不是相關技能名稱 – 2010-06-05 20:44:56

+0

@OMG:我相信它會返回skills.name請解釋 – Hogan 2010-06-06 13:17:06

相關問題