MySQL过滤来自没有内容的外键的结果

标签 mysql sql

我有两个表:

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/

相关文章:

php - foreach 循环中的两个数组?

mysql - AWS RDS 手动快照是否增量存储?

mysql - 根据主键插入或更新

sql - 自增问题postgresql

sql - 序列不存在 ORA-02289

php - 当多行不存在时也将它们连接起来

mysql - 我如何在 ubuntu 服务器的 mysql 中导入我的数据库转储文件

mysql - 将列值作为 mysql 数据库中现有表名传递

sql - 带/不带传递参数的条件存储过程

sql - Django过滤与用户组具有一对一关系的项目