How to query multiple tables in PHP?

Asked

Viewed 617 times

-1

$sele = "SELECT * FROM videos WHERE video_titulo LIKE '%$name%' OR video_chaves LIKE '%$name%'";

$query = "SELECT * FROM usuarios WHERE n_nome LIKE '%$name%' OR n_usuario LIKE '%$name%'";

How to search both tables in one query? Thus:

$search="SELECT * FROM tabela1, tabela2....."
  • You want to make a join in both tables? Or just want to bring all fields of two tables?

  • make a query and display the two tables in a single search for users and videos

  • What is your database?

  • I couldn’t understand your comment. Exibir as duas tabelas, you meant exibir o resultado das duas tabelas?

  • yes in a single consuta

  • $query = $Conn -> query "SELECT * FROM usuarios WHERE n_name LIKE '%$name%' OR n_usuario LIKE '%$name%'";

  • 1

    Have you ever tried to do the same in your last example? It would be something like SELECT t1.*, t2* FROM tabela1 t1, tabela2 t2. Although I don’t see a clear reason why you want to do this, this query should work.

Show 2 more comments

1 answer

5

You can use the command UNION.

SELECT * FROM TABELA_1
UNION
SELECT * FROM TABELA_2

ATTENTION

But to use this command the tables must have the same number of columns!

OBJECTION

"All right, but no. And now ?"

SOLUTION

Put in the SELECT only the fields you will need to make the query, being the same amount also.

EXAMPLE

SELECT ID, NOME AS RESULTADO FROM TABELA_1
UNION
SELECT ID, DESCRICAO AS RESULTADO FROM TABELA_2
  • the part AS RESULT means that?

  • It means I gave one alias for both fields, for you to use in your PHP. It’s just for ease.

  • @Diegosouza, another "move" is to do SELECT id, nome, x FROM tabela UNION SELECT null, nome, null. Works!

  • Yes, true. Cancel the columns.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.