苦苦挣扎写我的第一个连接查询

时间:2012-05-03 16:10:56

标签: sql

我有3张桌子,我试图在下面列出。我无法忍受。我没有做过很多查询,从来没有做过加入,我真的很困惑这是怎么回事。我将使用的示例查询将是简单的英语,

  

从skill_area获取所有portfolio_item_ids,其中web_design =“1”,       然后从portfolio_items获取具有portfolio_item_ids的id值的所有行       然后对于每一行,从portfolio_item_id等于portfolio_item_id的标签获取行,illustrator,photoshop或css之一的值为1。

QUERY我设法提出


SELECT portfolio_item_id

FROM skill_area s

WHERE web_design = 1


选择 *

FROM portfolio_items p

WHERE p.id = s.portfolio_item_id


选择 *

FROM 标签t

WHERE s.portfolio_item_id = t.portfolio_item_id


所以我认为这是正确的,我现在必须将它们加在一起


投资组合项目

id

ITEM_NAME

描述

技能区

portfolio_item_id

网页设计

品牌

打印

代码

portfolio_item_id

插画

的Photoshop

CSS

4 个答案:

答案 0 :(得分:2)

逐步分解,就像你在“普通英语”声明中所做的那样:

  1. 获取web_design skill_area的

    select * from skill_area where web_design = '1'
    
  2. 加入portfolio_items

    select * 
     from skill_area s, portfolio_items p 
     where web_design = '1' 
       and p.id = s.portfolio_item_id
    
  3. 加入标签,选择值= 1的行,只返回标签表中的列)

    select t.* 
     from skill_area s, portfolio_items p, tags t 
     where web_design = '1' 
       and p.id = s.portfolio_item_id
       and p.id = t.portfolio_item_id
       and t.value = '1'
    

答案 1 :(得分:1)

试试这个:

SELECT sa.portfolio_item_id, pi.*, subtags.*
FROM skill_area sa
INNER JOIN portfolio_items pi ON sa.portfolio_item_id = pi.id
INNER JOIN (SELECT CASE WHEN illustrator = '1' THEN 'illustrator' 
                        WHEN photoshop = '1' THEN 'photoshop' 
                        ELSE 'css' END as tag, portfolio_item_id 
            FROM tags) subtags ON sa.portfolio_item_id = subtags.portfolio_item_id
WHERE sa.web_design = '1'

您评论过您想要一个替代方案,只需从标记中获取所有列。

SELECT sa.portfolio_item_id, pi.*, tags.*
FROM skill_area sa
INNER JOIN portfolio_items pi ON sa.portfolio_item_id = pi.id
INNER JOIN tags ON sa.portfolio_item_id = tags.portfolio_item_id
WHERE sa.web_design = '1'

答案 2 :(得分:0)

SELECT      P.*
FROM        SkillArea S
INNER JOIN  Portfolio P ON S.portfolio_item_id = P.id
INNER JOIN  Tags T ON T.portfolio_item_id = P.id
WHERE       S.web_design = 1
AND         P.id = 1

答案 3 :(得分:0)

以下是这样的查询的样子。我试图逐字翻译你的英语变体以帮助你理解,并包括注释来描述疱疹。

select s.portfolio_item_id, p.*, t.*
from Skill_Area s                                 -- get all portfolio_item_ids from skill_area
inner join Portfolio_Items p on                   -- then get all the rows from portfolio_items
    p.portfolio_item_ids = s.portfolio_item_ids   -- with the id values of portfolio_item_ids
inner join Tags t on                              -- then for each row, get the row from tags
    t.portfolio_item_id = p.portfolio_item_id     -- where portfolio_item_id is equal to portfolio_item_id
    and t.portfolio_item_id = 1                   -- and the value of it is 1
where s.web_design = "1"                          -- where web_design = "1"