dsaaqdz6223 2011-02-04 10:50
浏览 34
已采纳

SQL查找相同的列数据

I have a table with around 15 columns. What I would like to be able to do, is select a range of IDs and have all column data that is the same, presented to me.

At the minute, I have it structured as the following:

SELECT id, col_a, col_b ... count(id)
FROM table
GROUP BY col_a, col_b ... 

Which returns rows grouped together that have identical data within all the rows - which is half what I want, but ideally I would like to be able to get a single row with either the value (if it's the same for every row id) or NULL if there is a single difference.

I'm not sure that it is possible, but I would rather see if it's doable in an SQL query than write some looping logic for PHP to go through and check each row's similarity.

Thanks,

Dan

UPDATE:

Just to keep this up-to-date, I worked through the problem by writing a PHP function that would find which were duplicates and then display the differences. However I have now since made a table for each column, and made the columns as references to the other tables.

E.G. In MainTable, ColA now refers to the table ColA

I'm still solving the problem with the PHP for the time being, mainly as I think it still leaves the problem mentioned above, but at least now Im not storing duplicate information.

  • 写回答

3条回答 默认 最新

  • duandazhen7306 2011-02-04 13:54
    关注

    Its a hairy thing to do, but you could do it similarly to how David Martensson suggested, I would write it like this, however:

    Select a.id, a.col1, a.col2, a.col3
    FROM myTable a, myTable b
    WHERE a.id != b.id
    and a.col1 = b.col1
    and a.col2 = b.col2
    and a.col3 = b.col3
    

    That would give you the ids that are unique, but each result would have the same values for columns 1, 2, and 3. However, I agree with some of the commenters to your question that you should consider an alternative data structure, as this could better take advantage of an RDBMS model. In that case you would want to have 2 tables:

    Table name: MyTableIds Fields: id, attrId

    Table name: MyTableAttrs Fields: attrId, attr1, attr2, attr3, ect

    In general, if you have data that is going to be duplicated for multiple records, you should pull it into a second table and create a relationship so that you only have to store the duplicated data 1 time and then reference it multiple times.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?