Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all fields from one table using INNER JOIN?

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?

like image 551
Klian Avatar asked Oct 02 '10 10:10

Klian


People also ask

How do I select all columns in inner join?

The INNER JOIN selects all rows from both participating tables as long as there is a match between the columns. An SQL INNER JOIN is same as JOIN clause, combining rows from two or more tables. SELECT * FROM table1 JOIN table2 ON table1. column_name = table2.

Which join gives all rows from both tables?

A FULL JOIN or FULL OUTER JOIN is essentially a combination of LEFT JOIN and RIGHT JOIN . This type of join contains all of the rows from both of the tables.

Can we apply inner join on same table?

It helps query hierarchical data or compare rows within the same table. A self join uses the inner join or left join clause. Because the query that uses the self join references the same table, the table alias is used to assign different names to the same table within the query.


2 Answers

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
like image 98
Martin Avatar answered Sep 22 '22 20:09

Martin


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
like image 33
Mitch Wheat Avatar answered Sep 22 '22 20:09

Mitch Wheat