我有两个表:
CREATE TABLE IF NOT EXISTS `test_category` (
`_id` int(11) NOT NULL AUTO_INCREMENT,
`score_type` varchar(50) NOT NULL,
`sub_code` int(11) NOT NULL,
`duration` varchar(10) NOT NULL,
`status` int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (`_id`),
KEY `sub_code` (`sub_code`)
)
CREATE TABLE IF NOT EXISTS `questions` (
`_id` int(11) NOT NULL AUTO_INCREMENT,
`question` varchar(255) NOT NULL,
`correct_ans` varchar(255) NOT NULL,
`incorrect1` varchar(255) NOT NULL,
`incorrect2` varchar(255) NOT NULL,
`incorrect3` varchar(255) NOT NULL,
`test_cat` int(11) NOT NULL,
`image_location` varchar(50) NOT NULL,
PRIMARY KEY (`_id`),
KEY `test_cat` (`test_cat`)
)
ALTER TABLE `questions`
ADD CONSTRAINT `questions_ibfk_1` FOREIGN KEY (`test_cat`) REFERENCES `test_category` (`_id`);
所以基本上这两个表是相关的。 questions 表通过引用 test_category _id 的表 questions 中的外键 test_cat 与 test_category 表相关。我不想显示的是 test_category 中的那些条目,这些条目在问题表中具有与之相关的条目。如果 test_category 中的条目没有从问题表中引用任何内容,则不应显示该条目。
select distinct test_category._id, test_category.score_type
from test_category join questions
where ??
这是我尝试过的sql,但我不知道如何用where来过滤它...
最佳答案
select distinct test_category._id, test_category.score_type from test_category
join questions
on 'questions.test_cat' = 'test_category._id'
关于MySQL过滤来自没有内容的外键的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24136829/