Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Distinct value over joined tables

Tags:

sql

join

I am trying to get the DISTINCT value of one column in a table. This column however is INNER JOINED from another table through an id.

When I try to use the DISTINCT on the column, it produces the same results because DISTINCT also takes into account the unique identifier ID. Is there any work around for this to just get the DISTINCT value of a column from a joined table???

EG.

SELECT val1, b.val2, val3
  FROM TABLE 1 
  JOIN (SELECT DISTINCT val2 
          FROM TABLE 2) AS b ON val1 = b.val2
like image 692
karlstackoverflow Avatar asked Feb 24 '12 04:02

karlstackoverflow


1 Answers

Try throwing in a GROUP BY instead of a DISTINCT:

SELECT val1
     , b.val2
     , val3
  FROM TABLE 1 
  JOIN (SELECT val2 
          FROM TABLE 2 GROUP BY val2) AS b ON val1 = b.val2
like image 151
northpole Avatar answered Sep 29 '22 01:09

northpole