选择不同的字段,但避免某些值
我有下表:
---------------------------
| id | capital_id | value |
---------------------------
| 1 | 1 | a |
---------------------------
| 2 | 2 | b |
---------------------------
| 3 | 2 | c |
---------------------------
| 4 | 2 | d |
---------------------------
| 5 | 3 | b |
---------------------------
| 6 | 3 | e |
---------------------------
| 7 | 4 | f |
---------------------------
我只需要选择不同的capital_id,但与给定值的不同。
为了更清楚,我将提供一个示例:如果我有 id=5 的记录,我需要获取所有不同 Capital_id,与 3 不同且值与 'b' 不同(所以要获取的capital_id是:1和4)。
我设法编写了类似于 SELECT id FROM table WHERE Capital_id != $capital_id AND value != $value 的查询,但是通过这种方式获取了重复的 Capital_id。我尝试添加 GROUP BY Capital_id
,但随后也获取了 Capital_id=2,尽管其值之一是“b”。
我该如何解决这个问题?
I have the following table:
---------------------------
| id | capital_id | value |
---------------------------
| 1 | 1 | a |
---------------------------
| 2 | 2 | b |
---------------------------
| 3 | 2 | c |
---------------------------
| 4 | 2 | d |
---------------------------
| 5 | 3 | b |
---------------------------
| 6 | 3 | e |
---------------------------
| 7 | 4 | f |
---------------------------
I need to select only distinct capital_id's, but different from one that has a value given.
To be more clear, I'll provide an example: If I have the record with id=5, I need to fetch all distinct capital_id's, different than 3 and with the value different from 'b' (so capital_id's to be fetched are: 1 and 4).
I managed to write the query like SELECT id FROM table WHERE capital_id != $capital_id AND value != $value
, but duplicate capital_id's are fetched this way. I tried to add a GROUP BY capital_id
, but then capital_id=2 is also fetched, although one of its values is 'b'.
How can I solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个。
Try this.