我有两张桌子:
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中所有tblEatables.Fruits,其中Edible_Status为0,而不是tblConfirm_Eatables中的那些。
示例数据:
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);
结果应该是:
Fruits Apple Papaya Jackfruit Pineapple Mango
注意“橙色”不存在,因为它的可食用状态为“1”。
答案 0 :(得分:3)
您可以使用LEFT JOIN
来确定水果是否存在于另一个表中,并且Edible_Status
不是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
然后WHERE
子句获取tblEatables
中不满足连接条件的所有行。
如果在Eatables_Id
表中的字段(Edible_Status
,tblConfirm_Eatables
)上构建复合索引,这可能会非常快。
答案 1 :(得分:2)
试试这个
SELECT fruits FROM tblEatables WHERE EatID
NOT IN
(SELECT Eatbles_Id WHERE Edible_Status = 1)
答案 2 :(得分:1)
我没有安装MySQL但是在SQL Server中安装了MySQL。试试这个
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
答案 3 :(得分:0)
要包含那些不在tblConfirm_Eatables中的水果,请使用left join。右表中的缺失值将采用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”前缀是多余的。你不妨放下它。