MySQL 查询:GROUP_CONCAT
我需要帮助构建查询。
我有两张桌子。一个称为 jobs_certs,另一个称为 users_certs。
jobs_certs 表包含申请职位所需的证书。每个所需的证书都有其自己的行,其中 job_id 代表所需证书所附加的职位发布,cert_id 代表附加到该证书的 ID。
users_certs 表包含用户拥有的所有证书。每个证书都有自己的行,其中 uid 代表用户的 id,cert_id 代表用户拥有的证书的 id。
我需要查看用户是否拥有该工作所需的所有证书。所以我尝试了这样的事情:
SELECT GROUP_CONCAT(cert_id) as certs, uid
FROM users_certs
HAVING certs = (SELECT GROUP_CONCAT(cert_id) FROM jobs_certs WHERE job_id = 6)
但我没有得到任何结果。类似这样的事情我该怎么办?
提前致谢。
I need help building a query.
I have two tables. One his called jobs_certs and the other is called users_certs.
The jobs_certs table contains the certificates required to apply for a job. Each required certificate has it's own row, with the job_id representing the job posting the required certificate is attached to, and cert_id representing the id attached to that certificate.
The users_certs table contains all the certificates a user possesses. Each certificate has it's own row, with the uid representing the user's id and the cert_id representing the id of the certificate the user possesses.
I need to see if a user possesses all the certificates required for the job. So I tried something like this:
SELECT GROUP_CONCAT(cert_id) as certs, uid
FROM users_certs
HAVING certs = (SELECT GROUP_CONCAT(cert_id) FROM jobs_certs WHERE job_id = 6)
But I'm not getting any results back. How should I go about something like that?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试一试吧。为作业证书创建一个内联视图,为用户证书创建另一个内联视图,然后在
cert_id
列表上将它们内部联接
在一起(确保有一个order by
中的GROUP_CONCAT
以使GROUP_CONCAT
的结果具有确定性):或者您甚至可以稍微修饰一下查询以返回所有用户,无论他们是否有所需的证书或不带有
hasRequiredCerts
列:Give this a go. Create an inline view for the job certs and another one for the user certs and then
inner join
them together on the list ofcert_id
(make sure that there is anorder by
in thatGROUP_CONCAT
to make the result of theGROUP_CONCAT
deterministic):Or you could even dress the query up a bit to return all users whether they have the required certs or not with a
hasRequiredCerts
column:关系模型的原则之一是列值应该是简单的而不是复合的;用白话来说,它被称为第一范式 (1NF)。虽然
GROUP_CONCAT
有有效的用途(它会产生非 1NF 的关系),但它会让您陷入困境。相反,应关注所需的结果:选择用户在某项工作中缺少的认证。您可以通过在认证 ID 上进行左连接或右连接来完成此操作,选择用户为 NULL 的那些行。如果没有缺失任何认证,则用户完全合格。或者,您可以选择
COUNT(jc.cert_id)
来获取缺少的认证数量。One of the tenets of the relational model is that column values should be simple rather than compound; in the vernacular, it's known as first normal form (1NF). While there are valid uses for
GROUP_CONCAT
(which produces a relation that's not 1NF), it's tripping you up here. Instead, focus on the desired results: select the certifications that a user is missing for a job. You can do this with a left or right join on the certification ID, selecting those rows where the user is NULL.If there are no missing certifications, the user is fully qualified. Alternatively, you can select
COUNT(jc.cert_id)
to get the number of missing certifications.