如何查询从数据库表中查找公共值

时间:2014-06-10 12:39:43

标签: php mysql

我需要帮助。下面是我的表

ID | method  | country | state | zip |   
---+---------+---------+-------+-----+    
 1 | method1 |     C   |   -   |   - |    
 2 | method2 |     C   |   S   |   - |    
 3 | method3 |     C   |   S   |   - |    
 4 | method4 |     C   |   -   |   Z |    
 5 | method5 |     C   |   S   |   Z |   
 6 | method6 |     C   |   -   |   Z |

现在我需要查询,如果我搜索ID(1,2,4) 我应该得到这样的查询结果(因为s存在于method2而z存在于method4)

County | State | zip
 C     | S     | Z

如果我搜索id(1,2) 我应该得到像那样的查询结果

County | State | zip
 C     | S     | -

如果我搜索id(1,4,6) 我应该得到像那样的查询结果

County | State | zip
 C     | -     | Z

请有人帮帮我。我怎么能用mysql查询得到这个。 可以肯定的是,每次我必须得到一行结果。

1 个答案:

答案 0 :(得分:0)

以下内容如何:

SELECT 
(
  SELECT County
  FROM MyTable
  WHERE ID IN (1,2)
  ORDER BY County DESC
  LIMIT 1
) AS County,
(
  SELECT State
  FROM MyTable
  WHERE ID IN (1,2)
  ORDER BY State DESC
  LIMIT 1
) AS State,
(
  SELECT zip
  FROM MyTable
  WHERE ID IN (1,2)
  ORDER BY zip DESC
  LIMIT 1
) AS Zip