如何从表中选择所有列但具有唯一的一列

时间:2016-12-14 11:40:41

标签: php mysql distinct

我有一个包含很多列的表格,我想要选择所有列,但我想要这些列中唯一的列。

这适用于我,但我没有获得所有专栏:

$result = mysql_query("SELECT DISTINCT company FROM table t $order");

我也对此进行了测试,但没有做任何事情:

$result = mysql_query("SELECT * DISTINCT company FROM table t $order");


$result = mysql_query("SELECT DISTINCT company * FROM table t $order");

修改

我的桌子上有很多列,我们说它有5个,所以我的记录就是这样的例子:

company   x      y     price   numOfEmpl
one       1      5     1.3     15
one       2      6     1.4     15
two       3      7     1.5     16
three     4      8     1.6     17

所以我想削减第二行,并采取所有其他行。

2 个答案:

答案 0 :(得分:0)

根据额外信息编辑上一个答案

如果需要,可以在MySQL和SQL Server中为您提供解决方案

MySQL示例(使用用户变量/子查询)

CREATE TABLE SomeTable (company VARCHAR(20), x INT, y INT, price FLOAT, numOfEmploy INT);

INSERT INTO SomeTable 
(company, x, y, price, numOfEmploy) 
VALUES 
('one', 1, 5, 1.3, 15),
('one', 1, 6, 1.4, 15),
('two', 1, 7, 1.5, 16),
('three', 1, 8, 1.6, 17);

SET @count = NULL, @value = NULL;
SELECT company, x, y, price, numOfEmploy FROM (
    SELECT 
        company, x, y, price, numOfEmploy,
        @count := IF(@value = company, @count + 1, 1) AS rc,
        @value := company
    FROM SomeTable
) AS grouped_companies WHERE rc = 1

SQL Server示例(使用CTE)

--Create the table
declare @sometable table ( company varchar(10), x int, y int, price float, numOfEmploy int)

--insert the data
insert into @sometable values ('one', 1, 5, 1.3, 15)
insert into @sometable values ('one', 2, 6, 1.4, 15)
insert into @sometable values ('two', 3, 7, 1.5, 16)
insert into @sometable values ('three', 4, 8, 1.6, 17)

--WITH Common Table Expression
;WITH grouped_companies AS (
        SELECT *, 
        ROW_NUMBER() OVER(PARTITION BY company
                            ORDER BY company) AS rc
        FROM @sometable)
SELECT gc.company, gc.x, gc.y, gc.price, gc.numOfEmploy
FROM grouped_companies gc
WHERE gc.rc = 1

答案 1 :(得分:0)

DISTINCT关键字可用于仅返回已定义列中的不同(不同)值,例如

SELECT DISTINCT column_name,column_name

或者您可以按

返回DISTINCT值的数量
SELECT COUNT(DISTINCT column_name)

See some samples on W3Schools

我认为您可能需要为所有记录使用单独的sql query