How do one query depend on the result of the other?

Asked

Viewed 73 times

0

Consider the following table:

+----+----------------+----------------+--------+
| ID | fk_resource_id | fk_language_id | value  |
+----+----------------+----------------+--------+
| 1  | 1              | 1              | Entrar |
+----+----------------+----------------+--------+
| 2  | 1              | 2              | Login  |
+----+----------------+----------------+--------+

It is necessary to make a select with filter through the columns value and fk_language_id:

... WHERE value LIKE '%Ent%'

The result of the above query will be:

+----+----------------+----------------+--------+
| ID | fk_resource_id | fk_language_id | value  |
+----+----------------+----------------+--------+
| 1  | 1              | 1              | Entrar |
+----+----------------+----------------+--------+

Notice that there is the column fk_resource_id. I need all field records returned fk_resource_id based on the result of the first query.

The result would be as follows:

+----+----------------+----------------+--------+
| ID | fk_resource_id | fk_language_id | value  |
+----+----------------+----------------+--------+
| 1  | 1              | 1              | Entrar |
+----+----------------+----------------+--------+
| 2  | 1              | 2              | Login  |
+----+----------------+----------------+--------+

I know it’s the same result as the initial table, but there are 2 points to consider:

  1. The original table has much more records and I only used 2 as an example.
  2. I cannot go to the first query o fk_resource_id, since the search is for records that have a certain string in the column value.

Update: i don’t need to join 2 tables. You need to filter the table by field value and based on the query result get all records that have the same fk_resource_id resulting from the first query. Here we have feathers 1 table and the INNER JOIN joins everything into a single Row, what I need is new Rows, like the above example.

  • 3

    The clause in wouldn’t solve it? For example: select * from Tabela where fk_resource_id in (select fk_resource_id from Tabela where value LIKE '%Ent%')?

  • 1

    or the Exists clause... puts it in Sqlfiddle that helps when exemplifying

1 answer

1


The search should be performed as follows:

SELECT
    T1.CAMPO1, T1.CAMPO2, T1.CAMPO3
FROM
    TABELA T1
WHERE
    T1.CAMPO2 IN (SELECT T2.CAMPO2 FROM TABELA T2 WHERE T2.CAMPO3 LIKE '%Ent%')
  • 4

    Your code may generate error once you used = but the subquery can return more than one record, because of the like. The most recommended would be to use in as I had commented

  • True, I’ll change the answer.

  • 3

    It is interesting to explain why the structure used to teach "how to fish" and not just "giving the fish"

  • That’s right. Thank you!

Browser other questions tagged

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