This question already has answers here:
Query with multiple values in a column
(4 answers)
Closed 6 years ago.
I have 1 table, t1, around 500+ data row, I just show a sample data.
Data as below:
+--------+----------+-------------------+
| id | Name | category |
+--------+----------+-------------------+
| 1 | ABC | 6,9,25,27 |
+---------------------------------------+
My mysql query like below:
$gcategory = intval($_GET['cat']);
$test = DB::fetch_all("SELECT * FROM t1 WHERE category like '%$gcategory%' ORDER BY id DESC");
foreach($test as $te){
$list[] = $te;
}
But if $gcategory = '7'; the ABC also will appear in my $list[], but I just want when $gcategory = '6' || $gcategory = '9' || $gcategory = '25' || $gcategory = '27' then ABC only appear in my $list[]? how to fix this?
Thanks.
Please try like following way, you should use find_in_set php function when you finding from , seperated list of value:
$gcategory = intval($_GET['cat']);
$test = DB::fetch_all("SELECT * FROM t1 WHERE FIND_IN_SET("'.$gcategory.'", category) ORDER BY id DESC");
foreach($test as $te){
$list[] = $te;
}
Try using MySQL FIND_IN_SET() function
You query will be like this
"SELECT * FROM t1 WHERE FIND_IN_SET($gcategory,category) ORDER BY id DESC"
Related
I have a table like so:
User_Id Column1 Column2 Column3
1 Yes No Yes
2
I want to use mysql query to list all the column names (there are more than 3) which match the User_Id '1' and have a value of 'Yes'.
I get an error:
Trying to get property 'num_rows' of non-object
Here is what I have tried:
<?php $myStats = $mysqli->query("SELECT COLUMN_NAME FROM user_services.columns WHERE myColumn = 'Yes'");
if ($myStats->num_rows > 0) {
// output data of each row
while($row = $myStats->fetch_assoc()) {
$rows[] = $row; }
return $rows; ?>
Please can someone show me where I am going wrong?
Thanks in advance.
The CONCAT_WS function comes in handy here:
SELECT CONCAT_WS(',', IF(Column1='Yes', 'Column1', NULL),
IF(Column2='Yes', 'Column2', NULL),
IF(Column3='Yes', 'Column3', NULL)) AS columns
FROM user_services.columns
WHERE User_Id = 1;
If you have more than 3 columns, then you may add more terms to above CONCAT_WS call. Your problem mainly seems to be a SQL one, so I won't add any PHP code.
Note that your design might be better off if your column strings were spread across rows, rather than columns. For instance, consider the following alternative:
User_Id | number | val
1 | 1 | Yes
1 | 2 | No
1 | 3 | Yes
Then, if you wanted all column numbers which were yes for user 1, you could simply do:
SELECT
User_Id,
GROUP_CONCAT(number ORDER BY number) columns
FROM yourTable
WHERE
User_Id = 1
GROUP BY
User_Id;
Hi this is what I want to do:
to_id: 5
to_type: 1
from_id: 3
from_type: 2
I want to SELECT ALL WHERE to_id = 5 only if to_type = 1 AND I want to select * where from_id = 3 only if from_type = 2.
how can I do this in a single SELECT statement?
Looks like this is what you want
SELECT * FROM foobar WHERE (to_id = 5 AND to_type = 1) OR (from_id = 3 and from_type = 2)
That is, get all rows that either matches to_id = 5 and to_type = 1, or matches from_id = 3 and from_type = 2.
$query = "SELECT COUNT(id) FROM complaint WHERE ID_complntCategory = ?";
$complntCategory = $database->prepare($query);
try {
$complntCategory->execute(array());
$complntCategory->setFetchMode(PDO::FETCH_ASSOC);
foreach ($complntCategory as $key) {
$totaalM = $key['1'];
$totaalV = $key['2'];
$totaalG = $key['3'];
}
}
catch(PDOException $e) {
echo "Error";
}
Above you see my PHP code, and here is what I'm trying to do:
I'm trying to get the amount of rows from the table 'complaint' into 3 different variables (totaalM, totaalV and totaalG). The totaalM variable should contain the amount of rows 'WHERE ID_complntCategory = 1'.
For the other variables the 'ID_complntCategory' should be 2 and 3
('ID_complntCategory' is either 1, 2 or 3)
There should be a way where I don't have to write 3 queries, right?
I'm clearly approaching this the wrong way, and I'm not sure how I should tackle this problem...
What you are trying to do is called pivot rows into columns, but MySQL doesn't have pivot table operator like other RDBMS, but you cane use the case expression like this in one query:
SELECT
SUM(CASE WHEN ID_complntCategory = 1 THEN 1 ELSE 0 END) AS totaalM,
SUM(CASE WHEN ID_complntCategory = 2 THEN 1 ELSE 0 END) AS totaalV,
SUM(CASE WHEN ID_complntCategory = 3 THEN 1 ELSE 0 END) AS totaalG,
COUNT(Id) AS Total
FROM complaint;
Or you can make it shorter like this:
SELECT
SUM(ID_complntCategory = 1) AS totaalM,
SUM(ID_complntCategory = 2) AS totaalV,
SUM(ID_complntCategory = 3) AS totaalG,
COUNT(Id) AS Total
FROM complaint;
Demo
This will give you something like this:
| totaalM | totaalV | totaalG | Total |
|---------|---------|---------|-------|
| 2 | 3 | 1 | 7 |
Here you need some magic, involving special SQL and PDO features.
First, you need an SQL query that is giving you desired results in one query. To get that you need a GROUP BY operator:
SELECT ID_complntCategory, count(*) FROM complaint GROUP BY ID_complntCategory
it will give you counts split by ID_complntCategory.
Next, you can use one of PDO's magnificent features, PDO::FETCH_KEY_PAIR fetch mode, that will give you an array where key would be category id and value is count
$sql = "SELECT ID_complntCategory, count(*) FROM complaint GROUP BY ID_complntCategory";
$stmt = $database->prepare($sql);
$key = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
$totaalM = $key['1'];
$totaalV = $key['2'];
$totaalG = $key['3'];
note that you should never catch a PDO errors only to say "error". Let PHP error reporting to do it instead.
This question already has answers here:
How to return rows that have the same column values in MySql
(3 answers)
Closed 5 years ago.
I'm working on a tag system where an array (of tags) is queried and all rows with the same tags in the Tag column are selected.
The issue is that I used the IN condition which is a type of an OR function, which selected all the rows with the same tags as opposed to narrowing them down, for example.
Instead of narrowing down an image with tags like 'sun' and 'landscape' it would select all images with those tags.
What I'm looking for is an AND version of IN () or a substitute that can work with arrays.
This is just an example. In reality, the user can add as many tags as they want
+----+---------+---------+
| ID | ImageID | Tag |
+----+---------+---------+
| 1 | 2 | sun |
+----+---------+---------+
| 2 | 12 |landscape|
+----+---------+---------+
| 3 | 15 | field |
+----+---------+---------+
| 4 | 15 |landscape|
+----+---------+---------+
My code
$tag = $_POST['tag'];
$tag = preg_split("#/#", $tag);
$tag = implode("', '", $tag);
$query = "SELECT * FROM ComicStripTags WHERE `Tag` IN ('$tag')";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)){
$ID[] = $row['ImageID'];
}
Thanks
P.S. I'm not working in SQL, im working in PHP
You can do it using inner joins:
select * from TAGS a
inner join TAGS b
on a.ImageID = b.ImageID
where a.tag = 'field'
and b.tag = 'landscape'
According to your PHP code:
$joins = [];
$conditions = [];
foreach (preg_split("#/#", $_POST['tag']) as $index => $tag) {
$alias = "ComicStripTags_$index";
$joins[] = "ComicStripTags AS $alias" . ($index > 0 ? " ON ComicStripTags_0.ImageID = $alias.ImageID" : '');
$conditions[] = "$alias.Tag = '$tag'";
}
$query = sprintf("SELECT * FROM %s WHERE %s", implode(' INNER JOIN ', $joins), implode(' AND ', $conditions));
Assuming each ImageID can have only one of each tag, you can group by ImageID and select only rows where the count of tags equals the size of the input array.
SELECT ImageID FROM ComicStripTags
WHERE Tag IN ('landscape', 'field')
GROUP BY ImageID HAVING COUNT(Tag) = 2;
Alternatively you can do some ranking which would support partial tag matches as well:
SELECT
ImageID,
group_concat(Tag) as 'matched_tags',
count(*) as 'tag_matches'
FROM TAGS
WHERE Tag IN ( [list_of_tags] )
GROUP BY ImageID
HAVING tag_matches >= [minimum_number_of_tags]
ORDER BY tag_matches DESC
Hi I'm trying to get the num rows of every data that equal on the value produce by foreach loop here's my samp code
$query = $this->db->query("SELECT * FROM tblsamp");
foreach ($query->result() as $row){
$subquery = $this->db->query("SELECT * FROM other_table WHERE foo like '%$row->some_col%'");
echo $subquery->num_rows();
// Ill get the num rows here equal on the value of $row->som_col
}
Here's the sample output so you can visualize the data"
name | NoRows
name1 | 6
name2 | 6
name3 | 6
name4 | 6
the problem is if name1 detect '6' rows the name2,name3,name4. and so on will also output '6' rows which is that the number of rows on each name is different.
Why im getting the same result of name1?
Hoping for your answer guys! thanks!
Why don't you use group and count request ?
select t.name, count(*)
from tblsamp t
left join other_table on foo like concat('%',t.some_col,'%')
group by t.name