从mysql表中选择不同的值

时间:2015-06-18 10:42:15

标签: mysql

以下是示例tablename:item

ID value1 value2    value3
1 flower  rose      hello
2 flower  daisy     hello
3 animal  dog       crisis
4 flower  rose      Hint
5 tree    oak       make
6 tree    oak       made
7 bird    sparrow   hello
8 bird    starling  hello

我想要一个返回以下内容的mysql SELECT语句

value1  value2     value3
flower  rose       hello
flower  daisy      hello
bird    sparrow    hello
bird    starling   hello

这是一个小解释。 value1应该在表中大于1。如果在所有出现的情况下value1 = value2,即使不是一次也不显示。

id 1: value1 repeats 3 times(more than 1), and there are 2 unique values for value2, so display it
id 2: same as id 1
id 3: value1 is not repeated in the table, so do not display it
id 4: already displayed
id 5: value1 repeats 2 times but value2 is same, so do not display it

依旧......

2 个答案:

答案 0 :(得分:2)

我的回答:

mysql> select * from tbl;
+------+--------+----------+--------+
| id   | value1 | value2   | value3 |
+------+--------+----------+--------+
|    1 | flower | rose     | hello  |
|    2 | flower | daisy    | hello  |
|    3 | animal | dog      | crisis |
|    4 | flower | rose     | Hint   |
|    5 | tree   | oak      | make   |
|    6 | tree   | oak      | made   |
|    7 | bird   | sparrow  | hello  |
|    8 | bird   | starling | hello  |
+------+--------+----------+--------+
8 rows in set (0.00 sec)

mysql> select t1.* from tbl t1 join tbl t2 on t2.value1 = t1.value1 and t2.value2 != t1.value2 group by t1.value1, t1.value2;
+------+--------+----------+--------+
| id   | value1 | value2   | value3 |
+------+--------+----------+--------+
|    7 | bird   | sparrow  | hello  |
|    8 | bird   | starling | hello  |
|    2 | flower | daisy    | hello  |
|    1 | flower | rose     | hello  |
+------+--------+----------+--------+

答案 1 :(得分:-1)

你可以试试这个,

Select value1 ,value2 ,value3 
from xyz , yzx 
where xyz.id= yzx.id 
  and yzx.value3='Hello';