搜索相关两个表之间的SQL问题

时间:2010-06-09 00:30:42

标签: php sql mysql database

我正在为我的网络应用程序编写某种搜索引擎,但我遇到了问题。我有2个表首先是项目表:

PROJECTS TABLE

id                  int(11)         NO      PRI     NULL    auto_increment
employer_id         int(11)         NO      MUL     NULL     
project_title       varchar(100)    NO      MUL     NULL     
project_description text            NO              NULL     
project_budget      int(11)         NO              NULL     
project_allowedtime int(11)         NO              NULL     
project_deadline    datetime        NO              NULL     
total_bids          int(11)         NO              NULL     
average_bid         int(11)         NO              NULL     
created             datetime        NO      MUL     NULL     
active              tinyint(1)      NO      MUL     NULL     

PROJECTS_SKILLS表

project_id          int(11)         NO      MUL     NULL     
skill_id            int(11)         NO      MUL     NULL     

例如:我想问这个查询到数据库:

1-) Skills are 5 and 7.
2-) Order results by created
3-) project title contains "php" word.
4-) Returned rows should contain projects.* columuns.
5-) Projects should be distinct(i don't want same projects in return of query).

请编写确保这些条件的sql查询。谢谢。

2 个答案:

答案 0 :(得分:3)

听起来你正在寻找一个EXISTS查询,它会验证表中是否存在匹配的行,但是没有执行JOIN。

SELECT *
FROM projects
WHERE EXISTS (SELECT 1 FROM projects_skills AS ps WHERE ps.project_id = projects.project_id AND ps.skill_id IN (5, 7))
    AND project_title LIKE '%php%'
ORDER BY created;

答案 1 :(得分:3)

SELECT projects.*
FROM projects
WHERE EXISTS (
        SELECT *
        FROM projects_skills
        WHERE skill_id = 5 
            AND project_id = projects.project_id
    )
    AND EXISTS (
        SELECT *
        FROM projects_skills
        WHERE skill_id = 7
            AND project_id = projects.project_id
    )
    AND project_title LIKE '%php%'
ORDER BY created

SELECT projects.*
FROM projects
WHERE EXISTS (
        SELECT *
        FROM projects_skills
        WHERE skill_id IN (5, 7) 
            AND project_id = projects.project_id
    )
    AND project_title LIKE '%php%'
ORDER BY created

取决于您的预期结果。