tags:

views:

155

answers:

6

In MySQL, I have a simple "SELECT * FROM foo" query. I would like to JOIN table 'bar', but:

  1. I only want one column from bar
  2. I specifically DON'T want the id column from bar, because it will conflict with the id column from foo

I know that I could use as statements to avoid name conflicts, but I don't want to complicate things. Is there a way to write this query without naming every column I want from foo?

In other words, can I say 'give me all the columns from foo and just this one column from bar?

Update: Why this is bad practice

Folks have pointed out that "SELECT *" is generally bad practice, because:

  • It returns unnecessary data. That could, now or in the future, include something large, like a BLOB data column.
  • If the database schema changes, the query may not return one of the expected columns. If the column is named explicitly in the query, there will be an error; if not, it may fail silently (insert a blank where a title should go, for example).
+8  A: 
SELECT foo.*, bar.whatever FROM ...

Note, however, that this is considered bad practice. You should always name all columns in the order you expect them to.

Alex Brasetvik
Bad practice as the order of the columns to be returned with `*` is arbitrary, you cannot guarantee the columns coming back.
Xepoch
"cannot guarantee the columns coming back"? i.e. something might prevent a column (or some records) from coming back on the join?
Hardryv
@Hardryv: The underlying schema can change as the database evolves.
Alex Brasetvik
Bad practice in also that some day you or someone else adds a BLOB or other large type to the table and suddenly you're returning 10MB of extra data
Chris Haas
@Chris - excellent point.
Nathan Long
+2  A: 

In SQL Server you can do this:

SELECT foo.*, bar.column FROM ...

I believe that it can be done in MYSQL as well.

Justin Swartsel
+1  A: 

write

SELECT foo.*, bar.id
FROM foo
JOIN bar
ON …
knittl
A: 

can you try?

select f.id, b.* from foo f,bar b
Ozan BAYRAM
A: 
SELECT x.*, y.specific 
FROM x 
JOIN y on x.id = y.id 
...
rmn
A: 
Chris G