1

I have a table products and another table categories.
Here is some sample data
Products

id    |  product_name      |  category_id
1     |  Leath Machine     |  1
2     |  Drilling Machine  |  1
3     |  Boring Machine    |  1

And here is category table

id    |   name           | symbol
1     |   SMT Equipment  | SMT

I want to do a select which will display me results like this

id    |  product_name      |  category_id  |  code
1     |  Leath Machine     |  1            |  SMT00001
2     |  Drilling Machine  |  1            |  SMT00002
3     |  Boring Machine    |  1            |  SMT00003

How cai do that.

3 Answers 3

4
SELECT
  `products`.`id`,
  `product_name`,
  `category_id`,
  CONCAT(symbol, LPAD(products.id,5,'0')) AS code
FROM products
  INNER JOIN categories
    ON products.category_id = categories.id;

Here is the SQLFiddle results.

SQL Fiddle Demo

Sign up to request clarification or add additional context in comments.

Comments

2

try this

   select p.id,p.product_name,p.category_id,concat(symbol ,'0000',p.id) code from Products p
   inner join category c
   on p.category_id = c.id

DEMO SQLFIDDLE HERE

1 Comment

this will not bring the desired result if there are 10 or more products. it will still fetch 0000 as string which should have been incremented.
1

SELECT p.*, CONCAT(c.symbol, LPAD(p.id, 5, '0')) FROM products p INNER JOIN category c ON p.category_id=c.id;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.