duandian2725 2014-09-01 19:06
浏览 512
已采纳

MySQL SELECT COUNT(*)基于多个条件的两个表

I have some sort of logic/sql challenge. I have two tables that hold user data and are related by a id. I would like to select the count of rows based on conditions from the two tables.

Here are my tables.

table one

t_contacts
id  | name    | tel     | profession | email   | sex  | city    | state   |
int | varchar | varchar | int        | varchar | char | varchar | varchar |

table two

t_contacts_meta
cid                | interest     |
int (t_contact_id) | varchar      |

from the table, contacts are stored on the t_contacts table and their interest stored on the t_contacts_meta table. One contact could have multiple interests.

My issue is the SQL query. example

 SELECT COUNT(*) as count 
 FROM t_contacts 
 where `state`='$state' 
    AND `profession`='$profession' 
    AND `sex`='$sex' 
    AND (
        `t_contacts_meta.interest`='$interest_1' 
        OR `t_contacts_meta.interest`='$interest_2 
        OR `t_contacts_meta.interest`='$interest_n'
    )

The sql i provided above is not my working code its just an example. I dont even know how to go about the query.

Thanks for the help :)

  • 写回答

6条回答 默认 最新

  • duanlangwen9597 2014-09-01 19:12
    关注

    This is you're probably looking for:

    SELECT COUNT(C.id) AS [count]
    FROM t_contacts C
    INNER JOIN t_contacts_meta M ON M.cid = C.id
                                   AND M.interest IN ('interest_1', 'interest_2', 'interest_n')
    WHERE C.state = 'state_value'
        AND C.profession = 'profession_value'
        AND C.sex = 'sex_value'
    

    Hope this will help you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM