我们说我有一张这样的桌子
id col1 col2 col3 col4 col5 col6
1 1 2 3 4 5 6
2 2 1 4 3 6 5
3 1 1 2 3 4 5
我想要选择每个字段具有不同值的行。输出将是
id col1 col2 col3 col4 col5 col6
1 1 2 3 4 5 6
2 2 1 4 3 6 5
我知道你可以做到这一点
SELECT * FROM table
WHERE col1 <> col2 AND col2 <> col3...
但是这将需要永远这么多列。是否有特定的功能来确定所有列是否都是唯一的?
答案 0 :(得分:3)
您可以使用UNION ALL
SELECT id
FROM (
SELECT id, col1 AS col
FROM mytable
UNION ALL
SELECT id, col2
FROM mytable
UNION ALL
SELECT id, col3
FROM mytable
UNION ALL
SELECT id, col4
FROM mytable
UNION ALL
SELECT id, col5
FROM mytable
UNION ALL
SELECT id, col6
FROM mytable) AS t
GROUP BY id
HAVING COUNT(DISTINCT col) = 6
如果您希望选择所有列,则执行以下操作:
SELECT *
FROM mytable
WHERE id IN ( .... above query here ...)
不幸的是,MySQL没有UNPIVOT
运算符会使上述查询更简洁。
答案 1 :(得分:2)
比您的解决方案稍微冗长一点,但如果列数过大则无法完美扩展:
SELECT
* -- In actual live code you would of course never use '*'
FROM
MyTable
WHERE
col1 NOT IN (col2, col3, col4, col5, col6) AND
col2 NOT IN (col3, col4, col5, col6) AND
col3 NOT IN (col4, col5, col6) AND
col4 NOT IN (col5, col6) AND
col5 NOT IN (col6) -- Done as an IN just to be consistent
答案 2 :(得分:1)
试试这个我希望这会帮助你
select
(SELECT group_concat(DISTINCT col1) FROM table) as col1,
(SELECT group_concat(DISTINCT col2) FROM table) as col2,
(SELECT group_concat(DISTINCT col3) FROM table) as col3,
(SELECT group_concat(DISTINCT col4) FROM table) as col4