关于mySql的JOIN问题

时间:2013-06-24 08:11:45

标签: mysql sql

两张桌子,brand_gifts bg,giftcode gc:

表1:brand_gifts

id brand_id name

表2:礼品代码

id gift_id code usesleft

我用来检索数据的值是brand_gifts表中的brand_id。我需要的是一个元素列表,在表一brand_id = 1,这两个表由table1相关:id table2:gift_id(不是必需的,table1上的所有元素都与table2有关系,换句话说,不是所有的ID来自表一有table2上的gift_id,所以使用该关系我想查询所有brand_id = 1,其中也使用左边> 0.

我试过了:

SELECT gc.gift_id
FROM brand_gifts bg, giftcode gc
WHERE (
bg.brand_id =1
AND gc.gift_id = gc.id
AND gc.usesleft >0
)
LIMIT 0 , 30

但结果是错误的。

3 个答案:

答案 0 :(得分:1)

试试这个

SELECT gc.gift_id
FROM brand_gifts bg, giftcode gc
WHERE (
bg.brand_id =1
AND gc.gift_id = bg.id
AND gc.usesleft >0
)
LIMIT 0 , 30

答案 1 :(得分:1)

   SELECT gc.gift_id
    FROM brand_gifts bg, giftcode gc
   WHERE (
    bg.brand_id =1
    AND gc.gift_id = gc.id    <==
   AND gc.usesleft >0
   )
    LIMIT 0 , 30

您的错误在标记的行中显示,条件应为“gc.gift_id = bg.id”

   SELECT gc.gift_id
    FROM brand_gifts bg, giftcode gc
   WHERE (
    bg.brand_id =1
    AND gc.gift_id = bg.id    <==
   AND gc.usesleft >0
  )
    LIMIT 0 , 30

答案 2 :(得分:0)

SELECT gc.gift_id
FROM giftcode gc
LEFT JOIN brand_gifts bg
ON gc.gift_id = bg.id
WHERE gc.usesleft > 0