Choose from two tables without repeating all values

Let me clarify my question: "How to select rows from single table and cross-reference tables without duplicate values?"

I now have three tables, a cross reference table and two separate tables:

           Table jobs
╔══════════╦══════════════════════════╗
║ job_id   ║  details                 ║
╠══════════╬══════════════════════════╣
║  1       ║  Looking for hire...     ║
║  2       ║  We need help!...        ║3       ║  We are a store that...  ║4Help wanted...          ║
╚══════════╩══════════════════════════╝

      Table job2pos
╔═══════════╦═════════════╗
║  job_id   ║ position_id ║
╠═══════════╬═════════════╣110210212311313410
╚═══════════╩═════════════╝

        Table positions
╔═══════════════╦═══════════════╗
║ position_id   ║ position_name ║
╠═══════════════╬═══════════════╣10           ║  waitress     ║11           ║  cashier      ║12           ║  cook         ║13           ║  chef         ║
╚═══════════════╩═══════════════╝

When I execute this query:

$sql = "SELECT jobs.details, positions.name AS position FROM jobs
INNER JOIN job2pos ON jobs.job_id = job2pos.job_id
INNER JOIN positions ON job2pos.position_id = positions.position_id
WHERE job2pos.job_id IN (2)";
...
print_r($stmt->fetchAll(\PDO::FETCH_ASSOC));

And I get the following:

Array(
  [0] => Array ([details] => We need help!...
                [position] => Waitress)
  [1] => Array ([details] => We need help!...
                [position] => Cook)
)

Now I have 2 lines for the same job, but what I want looks like this:

Array(
  [0] => Array ([details] => We need help!...
                [position] => Array ([0] => Waitress
                                     [1] => Cook)
               )
)
  • If you could point to some unnecessary code that I have in my code, that would be great.
+4
source share
1 answer

, , , SQL-. , . sql.

nosql .

, , , multiple statements with one call.

mysqli:

MySQL . - .

mysqli_multi_query(). . , .

MySQL , , .

PDO Q & A:

$stmt   = $db->query("SELECT 1; SELECT 2;");
$stmt->nextRowset(); //Move to next statement result
var_dump( $stmt->fetchAll(PDO::FETCH_ASSOC) ); //SELCT 2 result
+1

Source: https://habr.com/ru/post/1660869/


All Articles