views:

74

answers:

3

Hi,

I want to get all fields from one table and use DISTINCT with the second table.

I have this:

SELECT stats.*, 
DISTINCT(visit_log.blog_id) AS bid 
FROM stats 
INNER JOIN visit_log ON stats.blog_id = visit_log.blog_id

But I get this error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DISTINCT(visit_log.blog_id) AS bid FROM stats INNER JOIN visit_log ON stats.blog' at line 1

Any idea ?

Thanks!

+1  A: 
SELECT stats.*, dr.blog_id
FROM stats
INNER JOIN (SELECT DISTINCT(visit_log.blog_id) AS bid FROM visit_log) AS dr 
      ON stats.blog_id = dr.blog_id
Mitch Wheat
Thanks for your reply, but I get: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(SELECT DISTINCT(visit_log.blog_id) AS bid FROM visit_log) drFROM statsINNER J'
Klian
A: 

Instead of joining against visit_log, you can construct a derived table containing only the distinct blog_id values.

select stats.*, v.blog_id 
from stats 
inner join ( select distinct blog_id from visit_log where stats.blog_id = visit_log.blog_id ) as v
Martin
Ive modified a bit your code and It works for my needs. thanks!
Klian
A: 

You are only selecting blog_id from visit_log which is the column you are joining on. So your query is much like:

select * 
from stats s 
where 
exists (select null from visit_log v where s.blog_id = v.blog_id)
Lord Peter
Your query works, but only select the columns of "stats" table, I want to select the columns of visit_log too. Ive tried with: ....select * from visit_log v where s.blog_id = v.blog_id but it doesnt work
Klian