假设我在col1
中有col2
,col3
,col4
,myTable
列,我需要打印仅限于值的值一栏。
所以,如果上面看起来像
col1 col2 col3 col4
s e c b
c c a s
n s e a
d d q c
然后输出应为 n,q b ,因为它们分别仅对col1
,col3
和col4
是唯一的。
如何通过mysql php中的查询实现此目的?
编辑重复项不必排成一行。我现在更改了表格布局以使其清晰。
答案 0 :(得分: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
组合在一起,但这可能不是必需的,具体取决于您要对数据执行的操作。此外,此查询不适用于大型数据集。
答案 1 :(得分: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)
答案 2 :(得分: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'];
}
我猜这应该有效。不要尝试使用该代码,但请注意这一点,并告诉我们。
答案 3 :(得分: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)