我需要你的SQL请求帮助。这是我的表格:
表事件:
id | idType | used_by
1 1 Marc
2 1
3 1 Henry
表类型:
id | name | activate
1 Type 1 0
2 Type 2 1
如您所见,我有1型灭活,但有2人正在使用它。我希望显示已激活类型的事件中的记录,并显示某人使用的记录,即使该类型未激活。
下面的SQL仅显示类型已激活的事件:
CREATE TABLE events (id int(11), idType int(11), used_by varchar(50));
INSERT INTO events VALUES (1, 1, ''), (2, 1, 'Marc'), (3, 1, 'Henry'), (4, 2, ''), (5, 2, 'Sandy');
CREATE TABLE types (id int(11), name varchar(50), activate int(1));
INSERT INTO types VALUES (1, 'Type1' , 0), (2, 'Type 2', 1);
SELECT events.id, types.name, events.used_by
FROM events
INNER JOIN types
ON events.idType = types.id
WHERE types.activate = 1
这是sqlfiddle:sqlfiddle.com/#!9/7a36f/1,因此我希望从事件ID:2,3,4,5
答案 0 :(得分:1)
只需为used_by字段添加OR条件:
SELECT events.id, types.name, events.used_by
FROM events
INNER JOIN types
ON events.idType = types.id
WHERE types.activate = 1
OR events.used_by != ''
编辑以替换events.used_by根据更新的信息检查以查找非空白而非空。
答案 1 :(得分:1)
尝试使用
SELECT events.id, types.name, events.used_by FROM events INNER JOIN types ON events.idType = types.id WHERE types.activate=1 or trim(events.used_by)<>''
或者
SELECT events.id, types.name, events.used_by FROM events INNER JOIN types ON events.idType = types.id WHERE types.activate=1 or not isnull(events.used_by)
答案 2 :(得分:1)
Select e.*
from evsnts e
join types t on t.id = e.idtype
where t.Activate = 1 or
(e.used_by is not null and len(e.used_By) > 0)
答案 3 :(得分:0)
如果我理解错误,请纠正我,你想要显示事件表中的所有记录,这些记录由某人使用,无论激活或停用类型,
为此你可以在事件表上简化qyery
从used_by不为null且used_by!=''
的事件中选择*