简体   繁体   English

选择所有列数据但列上不同

[英]Select all column data but distinct on column

SELECT * DISTINCT `contact_id`  
 FROM `survey_response_single`  
  WHERE text_id = '1' LIMIT 0, 15 

i will want to fetch all columns data using distinct query 我将要使用不同的查询来获取所有列数据

First of all, it looks like he wants to access all the columns. 首先,看起来他想访问所有列。 So while using DISTINCT, one has to specify all the columns but as you can't use * 因此,在使用DISTINCT时,必须指定所有列,但是您不能使用*

But if we use GROUP BY, this problem could be solved. 但是,如果我们使用GROUP BY,则可以解决此问题。 As in GROUP BY you will get only distinct values of contact_id as similar values would be grouped. 与在GROUP BY中一样,您将仅获得contact_id不同值,因为相似值将被分组。 Moreover now we can access all columns using * 而且,现在我们可以使用*访问所有列

SELECT * FROM `survey_response_single`  
WHERE text_id = '1' 
GROUP BY `contact_id`

Try below of any depends on which output you want: 请尝试以下任何一种,具体取决于所需的输出:

SELECT DISTINCT contact_id, text_id, details  -- take your column names
FROM survey_response_single  
WHERE text_id = '1' LIMIT 0, 15 

http://sqlfiddle.com/#!2/3d502/4 http://sqlfiddle.com/#!2/3d502/4

or this(if you want only single column's distinct values): 或此(如果您只希望单列的不同值):

SELECT DISTINCT contact_id
FROM survey_response_single  
WHERE text_id = '1' LIMIT 0, 15 

http://sqlfiddle.com/#!2/3d502/6 http://sqlfiddle.com/#!2/3d502/6

Easy going: 随和:

SELECT DISTINCT `contact_id`, *
FROM `survey_response_single`
WHERE `text_id` = '1' LIMIT 0, 15

What many doesnt know: '*' doesnt have to be the only statement within a SELECT. 很多人不知道的是:*不必是SELECT中的唯一语句。 You can easily seperate it by comma and fetch more columns. 您可以轻松地用逗号分隔它并获取更多列。

You call DISTINCT on the target column and also fetch all other columns with star. 您可以在目标列上调用DISTINCT,也可以使用星号获取所有其他列。

The only side-effect is that your result table will contain two "contact_id" columns with identical content. 唯一的副作用是您的结果表将包含两个具有相同内容的“ contact_id”列。 But you dont need to worry about an alias when fetching the array with PHP this will work either way. 但是,使用PHP提取数组时,您无需担心别名,这两种方式都可以工作。

If you want a query without duplicate data you have no choice but to list all columns of the table by yourself instead of using * 如果要查询没有重复数据的查询,别无选择,只能自己列出表格的所有列,而不要使用*

$query=mysql_query("SELECT DISTINCT `contact_id`,column1,
column2 FROM `survey_response_single`
WHERE text_id = '1' LIMIT 0, 15  "); //You select here the required data 
//of column1,2... and having distinct contact_id values
$execute_query=mysql_query($query,$db_conn);
while($row=mysql_fetch_array($execute_query){
  //use you data
}
SELECT DISTINCT `contact_id`  
 FROM `survey_response_single`  
  WHERE text_id = '1' LIMIT 0, 15 

star (*) is not require 不需要星号(*)

SELECT  DISTINCT `contact_id`  
 FROM `survey_response_single`  
  WHERE text_id = '1' LIMIT 0, 15 

remove * sign 删除*号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM