2

我有两张桌子:

CREATE TABLE tblEatables (
    `EatId` int UNSIGNED PRIMARY AUTO_INCREMENT,
    `Fruits` varchar(9) NOT NULL
) Engine=InnoDB;

CREATE TABLE tblConfirm_Eatables (
    Eatables_Id INT UNSIGNED,
    Edible_Status INT,
    FOREIGN KEY Eatables_Id REFERENCES tblEatables (EatId)
) Engine=InnoDB;

我想选择 tblConfirm_Eatables 中 Edible_Status 为 0 的所有 tblEatables.Fruits,以及不在 tblConfirm_Eatables 中的所有 tblEatables.Fruits。

样本数据:

INSERT INTO tblEatables
(`EatId`, `Fruits`)
    VALUES
(1, 'Apples'),
(2, 'Oranges'),
(3, 'Papaya'),
(4, 'Jackfruit'),
(5, 'Pineapple'),
(6, 'Mango');

INSERT INTO tblConfirm_Eatables
    VALUES
(1,0),
(2,1),
(3,0),
(4,0);

结果应该是:

  水果
  苹果
  番木瓜
  菠萝蜜
  菠萝
  芒果

注意“橙色”不存在,因为它的可食用状态为“1”。

4

4 回答 4

3

You can use a LEFT JOIN to first determine whether or not the fruit exists in the other table and has an Edible_Status that's not 0.

SELECT    a.Fruits
FROM      tblEatables a
LEFT JOIN tblConfirm_Eatables b ON 
          a.EatId = b.Eatables_Id AND
          b.Edible_Status > 0
WHERE     b.Eatables_Id IS NULL

Then the WHERE clause gets all rows in tblEatables which don't satisfy the join condition.

This can be really fast if you build a composite index on fields (Eatables_Id, Edible_Status) in the tblConfirm_Eatables table.


SQLFiddle Demo

于 2012-07-27T05:20:01.167 回答
2

尝试这个

SELECT fruits FROM tblEatables WHERE EatID 
 NOT IN
 (SELECT Eatbles_Id WHERE  Edible_Status = 1)
于 2012-07-27T05:23:28.920 回答
1

我没有安装 MySQL,但在 SQL Server 中安装了。尝试这个

SELECT e.EatId,e.Fruits
FROM @tblEatables e 
LEFT JOIN @tblConfirm_Eatables ce ON e.EatId = ce.Eatbles_Id
WHERE ce.Edible_Status  = 0 OR ce.Edible_Status IS Null

结果

EatId   Fruits
1   Apples
3   Papaya
4   Jackfruit
5   Pineapple
6   Mango
于 2012-07-27T05:29:14.893 回答
0

要包含那些不在 tblConfirm_Eatables 中的水果,您可以使用左连接。右表中的缺失值将采用 NULL 值。你的陈述

有 Edible_Status 为 0 和那些不在 tblConfirm_Eatables

因此转化为

tblConfirm_Eatables.Edible_Status = 0 OR tblConfirm_Eatables.Edible_Status IS NULL

整体声明将如下所示:

SELECT Fruits
  FROM tblEatables AS E
    LEFT JOIN tblConfirm_Eatables AS CE ON E.EatID = CE.Eatables_ID
  WHERE CE.Edible_Status = 0 OR CE.Edible_Status IS NULL

无关

添加到表名的“tbl”前缀是多余的。你不妨把它关掉。

于 2012-07-27T05:20:58.470 回答