简体   繁体   中英

How to select multiple rows from the same table only using one query?

I have one table from MySQL and I want to select some rows from this table without having to use lots of queries to find single rows.

My code currently is something like that :

$query = "SELECT def_conteudo FROM conteudo WHERE nro_conteudo = '101' ";

$query2 = "SELECT def_conteudo FROM conteudo WHERE nro_conteudo = '102' ";

$query3= "SELECT def_conteudo FROM conteudo WHERE nro_conteudo = '103' ";

$query4 = "SELECT def_conteudo FROM conteudo WHERE nro_conteudo = '104' ";

And I don't like it, because for me it seems useless this code but I don't know a better way to find a solution to this, as I am new to PHP.

I want something like that if possible :

$query = "SELECT * FROM conteudo";

And while selecting all the table, I could choose what value I would display, without having multiple queries. How can I make that work ?

A couple of ways:

Using between:

SELECT def_conteudo FROM conteudo WHERE nro_conteudo BETWEEN 101 AND 104;

This fetches every row with an ID between those two number. If I remember correctly, the lower end is inclusive and the higher end is exclusive.

Alternatively, if they are not consecutive:

SELECT def_conteudo FROM conteudo WHERE nro_conteudo IN (101, 102, 103, 104); 

This will fetch the ID's in the list.

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