简体   繁体   中英

MySQL SELECT from two tables based on ID from URL

I have a problem. I'm new in MySQL. So far, I've needed only simple queries, and everything worked fine. But, now I have a problem. I have two tables:

  1. table tarife

     +----+---------------+ | id | ime_tarife | +----+---------------+ | 1 | Neka tarifa 1 | | 2 | Neka tarifa 2 | +----+---------------+ 
  2. table telefoni_dodatak

     +----+--------------+-----------+-------+ | id | telefoni_id | tarifa_id | price | +----+--------------+-----------+-------+ | 1 | 35 | 1 | 650 | | 2 | 35 | 2 | 700 | +----+--------------+-----------+-------+ 

All values in this table are integers.

I have URL like this www.example.com/phones/35/ where number 35 represents id of the page (used in some third table), and it's also writen as telefoni_id in table telefoni_dodatak .

Column tarifa_id have id numbers from table tarife .

I have to get output like this in HTML, based on id from url www.example.com/phones/35/ :

Neka tarifa 1 | 650
-------------------
Neka tarifa 2 | 700

I've tried with this query:

SELECT *, (SELECT ime_tarife FROM tarife WHERE id = (SELECT tarifa_id FROM telefoni_dodatak WHERE telefoni_id = :id)) AS nazivTarife FROM telefoni_dodatak WHERE telefoni_id = :id

but that don't work. ( nazivTarife is not defined. Should be?)

I'm using PDO, and :id is that number 35 from url.

PS This query SELECT * FROM telefoni_dodatak WHERE telefoni_id = :id works fine, I'm getting both prices 650 and 700.

Thanks in advance for any help!

why are you not joining it?

SELECT  a.ime_tarife, b.price 
FROM    tarife a
        INNER JOIN telefoni_dodatak b
            ON a.id = b.tarifa_id 
WHERE   b.telefoni_id = 35

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM