Search code examples
mysqlselectinner-join

How to select multiple fields in MySQL query when using INNER JOIN


I want to select multiple fields from table p.

The second line of this code is wrong. how to write?

except p.*

I don't want p.*

SELECT
      p.id, title, price
      c.`title` as `CategoryTitle`
      from `tbl_products` p
      INNER JOIN `tbl_categories` c
      ON p.`category_FK` = c.`id`

Solution

  • Well, you might have your own reason so, perhaps you can do something like this:

    SELECT
          id, title, price, CategoryTitle
       FROM `tbl_products` p
          INNER JOIN 
            (SELECT `title` AS 'CategoryTitle', id AS 'CategoryID' 
               FROM `tbl_categories`) c
          ON category_FK = CategoryID
    

    Make one of the table as a subquery and define column alias that's not a duplicate with the other table. In your example, it seems like both of your tables have columns with similar names like id & title. Once you define those similar column names in the subquery with different alias, then you won't need to do p.xx or c.xx.