我在使用MySQL查询时遇到了一些麻烦。
查询是从两个表中提取的。两个表都包含数据,但我只想要第二个表中的count(*)。
SELECT m.*, (SELECT COUNT(*) FROM cd_members_offers WHERE mo.mo_member_id = m.m_id) as mo_count
FROM cd_members m, cd_members_offers mo
/* these are variables and don't always exist */
WHERE (m.m_fname LIKE '%Richie%' OR m.m_lname LIKE '%Richie%' OR m.m_email LIKE '%Richie%')
AND (m.m_signupdate >= 20130807 AND m.m_signupdate <= 20130810)
AND m.m_add_state = 'QLD'
AND (mo_count >= '2' AND mo_count <= '5')
/* this is the end of the variables */
AND mo.mo_member_id = m.m_id
ORDER BY m.m_id ASC
/ *引号* /实际上并不存在于代码中。我只想展示如果输入所有变量,查询可能会如何查看。
我首先遇到了问题,其中会出现许多重复项。我也非常有信心mo_count&gt; =不是正确的方法。
我还在玩代码并做更多研究,但如果有人能够节省我一些时间,我真的很感激。
答案 0 :(得分:0)
试试这个
SELECT m.*, (SELECT COUNT(*) FROM cd_members_offers mo WHERE mo.mo_member_id = m.m_id) as mo_count
FROM cd_members m
/* these are variables and don't always exist */
WHERE (m.m_fname LIKE '%Richie%' OR m.m_lname LIKE '%Richie%' OR m.m_email LIKE '%Richie%')
AND (m.m_signupdate >= 20130807 AND m.m_signupdate <= 20130810)
AND m.m_add_state = 'QLD'
AND (mo_count >= '2' AND mo_count <= '5')
/* this is the end of the variables */
ORDER BY m.m_id ASC
或者可以使用Group By with having子句
SELECT m.m_id, count(mo.mo_member_id)
FROM cd_members m,cd_members_offers mo
/* these are variables and don't always exist */
WHERE (m.m_fname LIKE '%Richie%' OR m.m_lname LIKE '%Richie%' OR m.m_email LIKE '%Richie%')
AND (m.m_signupdate >= 20130807 AND m.m_signupdate <= 20130810)
AND m.m_add_state = 'QLD'
/* this is the end of the variables */
AND mo.mo_member_id = m.m_id
Group by m.m_id
having count(mo.mo_member_id) between 2 and 5
ORDER BY m.m_id ASC
答案 1 :(得分:0)
很难确定没有看到您的表架构,示例数据等,但您的查询可能看起来像这样
SELECT m.*, COUNT(mo_member_id) mo_count
FROM cd_members m LEFT JOIN cd_members_offers mo
ON mo.mo_member_id = m.m_id
WHERE (m.m_fname LIKE '%Richie%' OR m.m_lname LIKE '%Richie%' OR m.m_email LIKE '%Richie%')
AND m.m_signupdate >= '2013-08-07' AND m.m_signupdate <= '2013-08-10'
AND m.m_add_state = 'QLD'
GROUP BY m.m_id
HAVING mo_count BETWEEN 0 AND 5
示例输出:
| M_ID | M_FNAME | M_LNAME | M_EMAIL | M_SIGNUPDATE | M_ADD_STATE | MO_COUNT | -------------------------------------------------------------------------------------------------------- | 1 | Richie | Richie | richie@mail.com | August, 08 2013 00:00:00+0000 | QLD | 3 | | 2 | Richie2 | Richie2 | richie2@mail.com | August, 09 2013 00:00:00+0000 | QLD | 0 |
这是 SQLFiddle 演示