2

假设我有列col1, col2, col3, col4inmyTable并且我需要打印出只有一列独有的值

所以如果上面看起来像

  col1    col2    col3    col4
  s        e       c        b 
  c        c       a        s
  n        s       e        a
  d        d       q        c

那么输出应该是n, qb因为它们分别只对col1,col3和是专有的col4

如何通过 mysql php 中的查询来实现这一点?

编辑重复项不必在一行中。我现在更改了表格布局以使其清楚。

4

4 回答 4

1

如果您正在寻找仅 SQL 的解决方案,您可以像这样对每列进行查询:

SELECT 
    col1 AS unique_on_col1
FROM table
WHERE     col1 NOT IN (SELECT col2 FROM table)
      AND col1 NOT IN (SELECT col3 FROM table)
      AND col1 NOT IN (SELECT col4 FROM table)

可以将所有四个查询组合在一起,UNION但这可能不是必需的,具体取决于您要对数据执行的操作。此外,对于大型数据集,此查询不应该执行得很好。

于 2012-05-03T01:05:30.653 回答
1

一种更紧凑的方式来一次获取所有这些:

select distinct col1 
  from myTable 
 where col1 not in (select a.col1 
                     from myTable a join myTable b 
                       on a.col1 = b.col2 or a.col1=b.col3 or a.col1=b.col4)
 union
select distinct col2 
  from myTable 
 where col2 not in (select a.col2 
                     from myTable a join myTable b 
                       on a.col2 = b.col1 or a.col2=b.col3 or a.col2=b.col4)
 union
select distinct col3 
  from myTable 
 where col3 not in (select a.col3 
                     from myTable a join myTable b 
                       on a.col3 = b.col1 or a.col3=b.col2 or a.col3=b.col4)
 union
select distinct col4 
  from myTable 
 where col4 not in (select a.col4 
                     from myTable a join myTable b 
                       on a.col4 = b.col1 or a.col4=b.col2 or a.col4=b.col3)
于 2012-05-03T01:10:59.543 回答
0

尝试这个:

SELECT col1 AS unique_on_col1
FROM table
WHERE col1 NOT IN (SELECT col2 FROM table)
  AND col1 NOT IN (SELECT col3 FROM table)
  AND col1 NOT IN (SELECT col4 FROM table)
于 2012-05-03T10:55:17.257 回答
0
$sql = "
    SELECT DISTINCT 'col1' as descr,col1 as val FROM myTable
    UNION
    SELECT DISTINCT 'col2' as descr,col2 as val FROM myTable
    UNION
    SELECT DISTINCT 'col3' as descr,year as val FROM myTable";

$result = @mysql_query($sql, $con) or die(mysql_error());

while($row = mysql_fetch_array($result)) {
    $make_array[$row['descr']][]=$row['val'];
} 

我猜这应该可行。尝试一下代码,但试一试,让我们知道。

于 2012-05-03T00:49:16.227 回答