我有2个表投诉和任务。
投诉表在投诉表中是唯一的,即父表,它是任务表中的外键。
因此,一个投诉可以有多个任务,因此在任务表中您可以多次拥有相同的投诉ID。
我已经尝试了这一点,但是不能完全发挥作用,因为如果投诉有4个任务,并且只有1个任务被标记为完成,那么就会引起投诉:
SELECT * FROM complaints WHERE complaintID IN
(SELECT * FROM tasks WHERE completed="yes") ORDER BY deadline
如果有人可以帮我解决这个问题,我将不胜感激。
答案 0 :(得分:0)
select *
from complaints c
where not exists
(
select *
from tasks t
where t.ComplaintID = c.ComplaintID
and t.Completed <> 'yes'
)
答案 1 :(得分:0)
您只想在'inner'表中查找外键属性。所以,写这样: SELECT * FROM投诉WHERE complaintID IN (SELECT complaintId * FROM tasks WHERE completed =“yes”)ORDER BY截止日期 *或任务表上的外键
答案 2 :(得分:0)
已编辑
试试这个:
SELECT * FROM complaints
WHERE NOT EXISTS
(SELECT complaintid
FROM tasks
WHERE complaintid
in (SELECT complaintID
FROM tasks
WHERE tasks.complaintID = complaints.complaintid
and completed = 'no')
)ORDER BY deadline;
这是表结构和样本数据,如果用于测试我上面的答案。
CREATE TABLE complaints (
complaintID INT AUTO_INCREMENT PRIMARY KEY,
content VARCHAR(255),
deadline datetime
);
CREATE TABLE tasks (
tasksid INT AUTO_INCREMENT PRIMARY KEY,
complaintID INT,
completed ENUM ('yes','no')
);
INSERT INTO complaints(content,deadline) VALUES ('complaint1', NOW()+INTERVAL 3 day), ('complaint2',NOW()+INTERVAL 8 day),('complaint3', NOW()+INTERVAL 3 day);
INSERT INTO tasks (complaintID, completed) VALUES(1,'no'), (1,'yes'), (2,'yes'), (1,'no'), (1,'yes'), (1,'yes'), (2,'no'), (3,'yes'), (3, 'yes');
答案 3 :(得分:0)
你也可以这样做
select complaints.*, tasks.* from complaints, tasks where
complaints.complaintID=tasks.complaintID and tasks.completed='yes' and
complaints.complaintID NOT IN (select complaintID from tasks where completed='no')
使用的表格结构为:
CREATE TABLE complaints (
complaintID INT AUTO_INCREMENT PRIMARY KEY,
content VARCHAR(255),
deadline datetime
);
CREATE TABLE tasks (
tasksid INT AUTO_INCREMENT PRIMARY KEY,
complaintID INT,
completed ENUM ('yes','no')
);
INSERT INTO complaints(content,deadline) VALUES ('complaint1', NOW()+INTERVAL 3 day), ('complaint2',NOW()+INTERVAL 8 day);
INSERT INTO tasks (complaintID, completed) VALUES(1,'no'), (1,'yes'), (2,'no');
我使用了@Mr的表结构。激进,来自他的SQL FIDDLE。
希望有所帮助