online: 13; azi: 360; total: 52366 Webdesign - Phpmysql - 34

Select in doua tabele MySQL

In acest tutorial puteti invata cum se pot selecta coloane din doua tabele MySQL intr-o singura interogare.
Cand in comanda SQL sunt selectate coloane din tabele diferite, trebuie adaugat numele tabelului inainte de cel al coloanei (despartite prin punct "."). Sintax este:
SELECT `tabel1`.`coloana`, `tabel2`.`coloana` FROM `tabel1`, `tabel2` WHERE conditie

Sa vedem cateva exemple,in care se vor folosi urmatoarele doua tabele, denumite "categories" si "links".
categories
idcategory
1 PHP-MySQL
2 HTML
links
idlinkvisits
1 www.discant.ro/php-mysql/matrice_tablouri.html 12
1 www.discant.ro/php-mysql/siruri.html 15
2 www.discant.ro/html/tabele.html 18

1. Selectare toate coloanele din tabelul "categories" unde id=2, si coloanele "link" si "visits" unde visits>13.
SELECT `categories`.*, `links`.`link`, `links`.`visits` FROM `categories`, `links` WHERE `categories`.`id`=2 AND `links`.`visits`>13
Rezultat:
| id | category  |	              link              | visits |
------------------------------------------------------------------
| 2  |   HTML    | www.discant.ro/php-mysql/siruri.html |   15   |
| 2  |   HTML    | www.discant.ro/html/tabele.html      |   18   |


2. Selecteaza randurile din coloanele "category" si "link", unde 'id'-ul din tabelul 'categories' are valoarea 1, si id-ul din tabelul 'links' este egal cu id-ul din 'categories'.
SELECT `categories`.`category`, `links`.`link` FROM `categories`, `links` WHERE `categories`.`id`=1 AND `categories`.`id`=`links`.`id`
Rezultat:
| category  |                    link                        |
--------------------------------------------------------------
| PHP-MySQL | www.discant.ro/php-mysql/matrice_tablouri.html |
| PHP-MySQL | www.discant.ro/php-mysql/siruri.html           |

Doua SELECT intr-o interogare

Se poate de asemenea executa doua comenzi SELECT in aceeasi interogare SQL.
Exemple:

1. Selectare randuri din coloana "link" (tabel 'links') unde valoarea coloanei "id" corespunde cu id-ul pentru valoarea HTML (din tabelul 'categories').
SELECT `link` FROM `links` WHERE `id`=(SELECT `id` FROM `categories` WHERE `category`='HTML')
Rezultat:
|               link                  |
---------------------------------------
| www.discant.ro/html/tabele.html     |


2. Returneaza numarul total de randuri din tabelul 'links', unde visits>14, si se selecteaza inregistrarile din coloana "category" (tabelul 'categories') unde id<4.
SELECT (SELECT COUNT(*) FROM `links` WHERE `visits`>14) AS nrl, `category` FROM `categories` WHERE `id`<4
Rezultat:
| nrl | category  |
-------------------
|  2  | PHP-MySQL |
|  2  |   HTML    |

- Exista si o alta modalitate de a selecta coloane din doua tabele diferite, folosind instructiuni JOIN, prezentate in tutorialul MySQL INNER JOIN, LEFT JOIN, RIGHT JOIN.