Select distinct from multiple fields using sql

后端 未结 8 1782
难免孤独
难免孤独 2020-12-01 12:53

I have 5 columns corresponding to answers in a trivia game database - right, wrong1, wrong2, wrong3, wrong4

I want to return all possible answers without duplicates.

相关标签:
8条回答
  • 2020-12-01 13:52

    Well you can use a UNION and run 5 select statements, one for each column in your table. It would look something like this:

    SELECT right FROM answers
    UNION
    SELECT wrong1 FROM answers
    UNION
    SELECT wrong2 FROM answers
    UNION
    SELECT wrong3 FROM answers
    UNION
    SELECT wrong4 FROM answers
    

    This will give you a single list containing all the answers. You'll still have duplicates though if you have multiple copies of the same answer within a single column.

    0 讨论(0)
  • 2020-12-01 13:55

    Columns of "right, wrong1, wrong2, wrong3, wrong4" mean that you have a mis-designed database. In general, a number or letter suffix on a column name should be a red flag to rethink the problem.

    As you observed, your design required you to hack around to get a solution to a typical data reduction problem.

    0 讨论(0)
提交回复
热议问题