我有两张桌子:
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`);
所以基本上这两个表是相关的。问题表与test_category表有关,通过外键test_cat来自引用test_category的_id的表格问题。我要显示的是来自test_category的那些条目,它们在问题表中有与之相关的条目。如果test_category中的条目没有从问题表中引用它的任何内容,则不应显示它。
select distinct test_category._id, test_category.score_type
from test_category join questions
where ??
这是我试过的sql,但我不知道如何用哪里过滤它......
答案 0 :(得分:1)
select distinct test_category._id, test_category.score_type from test_category
join questions
on 'questions.test_cat' = 'test_category._id'
答案 1 :(得分:0)
select distinct test_category._id, test_category.score_type from test_category
join questions
on questions.test_cat = test_category._id
对Nisha和Abhik Chakraborty的称赞