我有一个表,其中user_id与用户所拥有的角色相关,因此不一定是1:1的用户角色,因为他可以拥有多个角色。
我希望只选择具有role_id = 2而不是任何其他角色的用户。你能帮忙吗?
select user_id, role_id
from users u
join roles r on u.user_id=r.user_id
(简单地添加where role_id=2
不正确)。
当前输出:
user_id role_id
1 2
1 other
1 3
2 2
3 0
预期产出:
user_id role_id
2 2
答案 0 :(得分:1)
以下是使用聚合的一种方法:
var fileList = [];
// only way to change input[type=file] value is with a other FileList instance
// and this is the only way to construct a new FileList
function createFileList(a) {
a = [].slice.call(Array.isArray(a) ? a : arguments)
for (var c, b = c = a.length, d = !0; b-- && d;) d = a[b] instanceof File
if (!d) throw new TypeError('expected argument to FileList is File or array of File objects')
for (b = (new ClipboardEvent('')).clipboardData || new DataTransfer; c--;) b.items.add(a[c])
return b.files
}
// This is what you got to do later when they remove a image
//
// this will trigger a change event so you maybe want to temporary
// turn off the change event listener
//
// input.files = createFileList(fileList)
// Image prev
// Multiple images preview in browser
function imagesPreview(input, imageContainer) {
$(imageContainer).empty();
var URL = window.URL || window.webkitURL;
var $html = $(
'<div class="image-item col-sm-6 col-md-4 col-lg-3">'+
'<div class="image-wrapper"> <img></div></div>'
);
$.each(input.files, function(i, file) {
var $clone = $html.clone()
// could be a good idea to revoke url also
$clone.find('img').attr('src', URL.createObjectURL(file))
$clone.appendTo(imageContainer);
fileList.push(file);
});
}
$('#input-image').on('change', function () {
imagesPreview(this, '.image-container');
});
如果select user_id, 2
from roles r
group by user_id
having min(role_id) = 2 and min(role_id) = max(role_id);
可能是role_id
,您可以将其调整为:
NULL
答案 1 :(得分:0)
试试这个,它也适用于NULL
:
SELECT user_id, 2 FROM (
SELECT user_id, COUNT(role_id)
FROM roles
GROUP BY user_id
HAVING MIN(role_id) = 2 AND MAX(role_id) = 2 AND COUNT(*) = COUNT(role_id)
) AS t;
这是巨大的,但我觉得这是在PostgreSQL中最简单的方法。