如何使用php和mysql从外表中搜索数据?

时间:2016-08-01 10:45:41

标签: php mysql

这是3个mysql表格式:

project_status

psid    p_id  cdid  sid  short_list  res_sent
1       3     112   24   0           0
2       3     113   25   0           1
3       4     114   22   0           1
4       4     115   23   1           0 
5       5     116   26   0           0  

contact_details:

cdid   family_name    given_name     department     title    cid
112    xx             xx             xx             xx       1
113    xx             xx             xx             xx       2
114    xx             xx             xx             xx       3
115    xx             xx             xx             xx       4
116    xx             xx             xx             xx       5

公司:

cid   company_name
1     xx
2     xx
3     xx
4     xx
5     xx

现在,我需要根据cdidproject_statusp_id表格中搜索sid以显示family_name, given_name, department, title

因此,我使用以下查询,我得到3个结果

SELECT
    cd.family_name,
    cd.given_name,
    cd.department,
    cd.title,
    cd.cid,
    ps.*, company.company_name
FROM
    contact_details AS cd
LEFT JOIN project_status AS ps ON cd.cdid = ps.cdid
LEFT JOIN company ON company.cid = cd.cid
WHERE
    1 = 1
AND ps.sid IN (25, 22)
AND ps.p_id = '3'
ORDER BY
    company.company_name ASC

现在我想再次根据 family_name或given_name或部门搜索字符串<搜索最后结果数据(这是3个结果)< / p>

为此,我使用以下查询:

SELECT
    cd.family_name,
    cd.given_name,
    cd.department,
    cd.title,
    cd.cid,
    ps.*, company.company_name
FROM
    contact_details AS cd
LEFT JOIN project_status AS ps ON cd.cdid = ps.cdid
LEFT JOIN company ON company.cid = cd.cid
WHERE
    1 = 1
AND ps.sid IN (25, 22)
AND company.company_name LIKE '%ab%'
OR cd.family_name LIKE '%ab%'
OR cd.given_name LIKE '%ab%'
AND ps.p_id = '3'
GROUP BY
    cd.cdid
ORDER BY
    company.company_name ASC

现在它不应该向我显示更多的结果,因为我在第一次查询时显示了3个结果。但不幸的是,它向我展示了来自contact_details table

的3个以上的结果

3 个答案:

答案 0 :(得分:1)

尝试修改sql的最后部分:

SELECT
cd.family_name,
cd.given_name,
cd.department,
cd.title,
cd.cid,
ps.*, 
company.company_name
FROM contact_details AS cd
LEFT JOIN project_status AS ps ON cd.cdid = ps.cdid
LEFT JOIN company ON company.cid = cd.cid
WHERE ps.sid IN (25, 22)
AND (company.company_name LIKE '%ab%' 
   OR cd.family_name LIKE '%ab%' 
   OR cd.given_name LIKE '%ab%' )
AND ps.p_id = '3'
GROUP BY cd.cdid
ORDER BY company.company_name ASC

答案 1 :(得分:0)

你的OR条款正在使你的标准远远超出你的想法

我认为这可能是您要指定的内容,但它有点猜测

1=1

this.dragulaService.over.subscribe((value:any) => { this.onOver(value); }); private onOver(args:any) { let [bag, element, target, source, smth] = args; } 完全没必要

答案 2 :(得分:0)

  SELECT cd.family_name, cd.given_name, cd.department, cd.title, cd.cid, ps.*, company.company_name 
  FROM contact_details AS cd 
  INNER JOIN project_status AS ps ON cd.cdid = ps.cdid 
  INNER JOIN company ON company.cid = cd.cid 
  WHERE ps.sid IN (25,22) AND ps.p_id = '3' 
  AND ( company.company_name LIKE '%ab%' OR cd.family_name LIKE '%ab%' OR cd.given_name LIKE '%ab%' ) 

  ORDER BY company.company_name ASC