Php Mysql查询无法正常工作

时间:2015-06-22 05:41:58

标签: php mysql

我有一个表名tblnetworkstatus,我有11列

  1. 编号
  2. issue_name
  3. affected_server
  4. affected_service
  5. ISSUE_TYPE
  6. 优先
  7. 持续时间
  8. 状态
  9. 起始日期
  10. END_DATE
  11. 描述
  12. 我在protected_server和affected_service中获取id,我将其存储在我的数据库中,现在我有三种情况

    1. 已选择affected_server和affected_service
    2. 仅选择affected_server
    3. 仅选择affected_service
    4. 我分别使用tblnetworkstatus,tblserver和tblproduct上的连接分别从tblserver和tblproducts获取affected_server和affected_service的名称我已经从这里获得了以下查询

      SELECT 
          m.issue_name ,m.issue_type ,
          m.priority ,m.status,m.description ,
          m.start_date,m.end_date,m.duration,
          s.name  as server_name,p.name as product_name
          from mod_networkstatus as m 
          LEFT JOIN  tblservers as  s  ON  m.affected_server=s.id
          LEFT JOIN tblproducts as  p  ON  m.affected_service=p.id
      

      但是如果我有多个来自affected_server和affected_service的id,就像我将1,2,3,4存储在一个列affected_server或affected_service中那么我该怎么做?

2 个答案:

答案 0 :(得分:0)

无需使用union,因为它会提供大量重复数据

您希望通过简单left joininner join

完成您想要实现的目标
    SELECT 
    m.issue_name ,m.issue_type ,
    m.priority ,m.status,m.description ,
    m.start_date,m.end_date,m.duration,
    s.name  as server_name,p.name as product_name
    from mod_networkstatus as m 
    LEFT JOIN  tblservers as  s  ON  m.affected_server=s.id
    LEFT JOIN tblproducts as  p  ON  m.affected_service=p.id
  

一列中的多个ID

    SELECT 
    m.issue_name ,m.issue_type ,
    m.priority ,m.status,m.description ,
    m.start_date,m.end_date,m.duration,
    s.name  as server_name,p.name as product_name
    from mod_networkstatus as m 
    LEFT JOIN  tblservers as  s  ON  FIND_IN_SET(m.affected_server,s.id)
    LEFT JOIN tblproducts as  p  ON  m.affected_service=p.id

看看这是否适合您。

答案 1 :(得分:0)

即使您的要求不是很清楚,仍然可以根据您的要求使用以下查询。

SELECT m.issue_name ,m.issue_type ,m.priority ,m.status,m.description ,m.start_date,m.end_date,m.duration,s.name  AS server_name,p.name AS product_name 
FROM  tblnetworkstatus m 
LEFT JOIN tblservers s ON m.affected_server=s.id 
LEFT JOIN tblproducts p ON m.affected_service=p.id 
WHERE ((m.affected_server='Y' AND m.affected_service='Y') OR m.affected_server='Y' OR m.affected_service='Y');

注意:如果不是您想要的,那么请分享所有3个表样本数据和您想要的输出,以便我可以帮助您。

根据您的最新更新,您可以尝试一下 -

SELECT m.issue_name ,m.issue_type ,m.priority ,m.status,m.description ,m.start_date,m.end_date,m.duration,s.name  AS server_name,p.name AS product_name 
FROM  tblnetworkstatus m 
LEFT JOIN tblservers s ON find_in_set(s.id,m.affected_server) 
LEFT JOIN tblproducts p ON find_in_set(p.id,m.affected_service) 
WHERE ((m.affected_server='Y' AND m.affected_service='Y') OR m.affected_server='Y' OR m.affected_service='Y');

注意:但这不是一个好主意,因为它不会使用索引并减慢过程。