P
P
primitiv2022-03-25 21:37:35
SQL
primitiv, 2022-03-25 21:37:35

How to get unique field values ​​based on another field?

Suppose there is a table with three fields id, product and color, product stores product types and color stores their colors, for example, product stores ten lighthouses and five sweaters, and color has 7 unique colors belonging to T-shirts (sweaters are not important), how to get all unique colors related to jerseys

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Slava Rozhnev, 2022-03-26
@primitiv

<?php

$product = 'sweater';
$query = "select distinct color from products where product = ?;";

// get DB version using PDO
$stmt = $pdo->prepare($query);
$stmt->execute([$product]);
$colors = $stmt->fetchAll(PDO::FETCH_ASSOC);

print_r($colors);

PHP PDO online test

I
Ivan, 2022-03-25
@FCKJesus

DISTINCT or GROUP BY will help you:
SELECT DISTINCT color FROM TableName;
SELECT color FROM TableName GROUP BY color;
The first option is more convenient for me.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question